Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React String Constants

I want to abstract all strings in my application to a centralized file. I could do the following:

strings.js:

export const MY_STRING = "foobar";

component.js:

import React, { Component } from "react";
import { MY_STRING } from "strings";

class MyComponent extends Component {
    render() {
        return <div>{MY_STRING}</div>
    }
}

But this seems like it could become slow at runtime for a large amount of interpolations. Is there a way to add these strings at build time via webpack to avoid interpolation?

like image 783
treyhakanson Avatar asked Feb 28 '26 23:02

treyhakanson


1 Answers

Use the Webpack Define plugin:

new webpack.DefinePlugin({
  SOME_VARIABLE: "Hello World",
});

Honestly though, there is no harm to just having the strings.js file, and it will make your application infinitely easier to reason about. Also, once you start getting more complex strings or doing string templating, then that has to be done at runtime and so you'll end up with a strings.js anyways. It would not be fun to have your strings split between Webpack config and strings.js.

like image 70
Matthew Herbst Avatar answered Mar 02 '26 11:03

Matthew Herbst