Search code examples
reactjswebpackgoogle-chrome-extensionwebpack-config

Accessing mode from webpack config


I have in webpack.config.js:

module.exports = {
    entry: {
        index: "./src/index.js",
        content: "./src/content.js"
    },
    mode: "production",             // How do I access this value from the React code?
    devtool: 'inline-source-map',
    ...

Depending on whether the mode is 'development' or 'production', I need to use a different client ID for PayPal (either sandbox or real). I would like to avoid duplication. So, how can I access that value from my React code?


Solution

  • You can access the mode by extending your module export into an arrow function. It is part of the second argument (args) which we can destructure. Use webpack define to change env variables.

    const PAYPAL_CLIENT_VARS = {
      production: "a",
      development: "b"
    };
    
    const bakeEnvironmentValues = (values, mode) => {
      return values[mode];
    };
    
    
    module.exports = (env, { mode }) => {
      // Useful for setting devTool, don't want to type this conditional everywhere
      const isDevMode = mode === 'development';
    
      return {
         ...webpack config go here,
        mode,
        plugins: [
           new webpack.DefinePlugin({
             PAYPAL_CLIENT: JSON.stringify(
                bakeEnvironmentValues(PAYPAL_CLIENT_VARS, mode)
        )}),
     ]
    
       }
    }
    
    

    You can then access that environment variable by referencing SOME_ENV (or whatever you call it) anywhere in the client side JS.