0

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?

AlwaysLearning
  • 7,257
  • 4
  • 33
  • 68

1 Answers1

0

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.

Vayne Valerius
  • 158
  • 1
  • 9
  • I don't see the connection between the parts. What do you need the Boolean `isDevMode` for? What is the `mode` variable you pass to `bakeEnvironmentValues`? How is this related to `module.exports`? And lastly, given all this in `webpack.config.js`, how do I access `mode` from the React code? – AlwaysLearning Aug 16 '23 at 14:53
  • I have updated my answer to hopefully be more understandable for you. 1) I used that instead of having that conditional everywhere I want to check if its dev mode in my config 2) The mode 3) Module exports is what wraps your webpack config. Its in your question!!! 4) Don't. Change the environment variables using it instead. Why would you access mode from the client code and not just change what you can access using it? There is no use case I can think of for the client side code to need to know if its dev or prod – Vayne Valerius Aug 17 '23 at 08:32
  • I think this is too complicated. All that was needed is to define a variable and then make it available to the rest of the code by defining a plugin. – AlwaysLearning Aug 17 '23 at 14:22
  • Isn't that what I have described here? You set a variable based on the mode and pass it as an environment variable using a plugin. – Vayne Valerius Aug 22 '23 at 08:51
  • Somehow I find your code confusing... But I'll accept it since it has the solution in it. – AlwaysLearning Aug 22 '23 at 17:22