Search code examples
javascriptreactjsminifybundling-and-minification

Minified JS find and replace a valid strategy for substitution?


For reasons not important to the question (using the output of create-react-app, would like to parameterize some variables POST build time i.e as they're deployed), I am in a scenario where I would like to replace all instances of a string i.e "REPLACE_ME" with a value.

This would be trivial if I had access to the un-minified javascript; however, I am wondering if a find and replace on the minified javascript will suffice?


Solution

  • create-react-app is using Webpack under the hood, You can use webpack.DefinePlugin to achieve that in a build time.

    // webpack.config.js
    const webpack = require('webpack');
    
    const config = {
      entry: './src/index.js',
      output: {
        ...
      },
      plugins: [
        new webpack.DefinePlugin({
          REPLACE_ME: JSON.stringify('yourBuildTimeValueGoesHere'),
        }),
        ...
      ],
      ...
    }
    
    module.exports = config;