Home  >  Q&A  >  body text

Access schema from webpack config

<p>I have the following code in <code>webpack.config.js</code>: </p> <pre class="brush:js;toolbar:false;">module.exports = { entry: { index: "./src/index.js", content: "./src/content.js" }, mode: "production", // How to access this value from React code? devtool: 'inline-source-map', ... </pre> <p>I need to use a different client for PayPal depending on whether <code>mode</code> is <code>'development'</code> or <code>'production'</code> ID (sandbox or real environment). I hope to avoid duplication. So, how do I access this value from my React code? </p>
P粉505917590P粉505917590401 days ago358

reply all(1)I'll reply

  • P粉547362845

    P粉5473628452023-08-18 15:42:58

    You can access this mode by extending the module export as an arrow function. It's part of the second argument (args) that we can deconstruct.

    module.exports = (env, { mode }) => {
      const isDevMode = mode === 'development';
    
      return {
         ...webpack配置在这里
       }
    }

    Then you can create client environment variables using something like webpack.define, for example:

    ## 在webpack配置之前
    
    const SOME_STUFF = {
      production: "a",
      development: "b"
    };
    
    const bakeEnvironmentValues = (values, mode) => {
      return values[mode];
    };
    
    
    ## 在plugins中
    
     new webpack.DefinePlugin({
         SOME_ENV: JSON.stringify(
             bakeEnvironmentValues(SOME_STUFF, mode)
      )}),

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

    reply
    0
  • Cancelreply