Passing environment-dependent variables in webpack

后端 未结 15 2175
醉酒成梦
醉酒成梦 2020-11-22 12:46

I\'m trying to convert an angular app from gulp to webpack. in gulp I use gulp-preprocess to replace some variables in the html page (e.g. database name) depending on the NO

15条回答
  •  爱一瞬间的悲伤
    2020-11-22 13:28

    I investigated a couple of options on how to set environment-specific variables and ended up with this:

    I have 2 webpack configs currently:

    webpack.production.config.js

    new webpack.DefinePlugin({
      'process.env':{
        'NODE_ENV': JSON.stringify('production'),
        'API_URL': JSON.stringify('http://localhost:8080/bands')
      }
    }),
    

    webpack.config.js

    new webpack.DefinePlugin({
      'process.env':{
        'NODE_ENV': JSON.stringify('development'),
        'API_URL': JSON.stringify('http://10.10.10.10:8080/bands')
      }
    }),
    

    In my code I get the value of API_URL in this (brief) way:

    const apiUrl = process.env.API_URL;

    EDIT 3rd of Nov, 2016

    Webpack docs has an example: https://webpack.js.org/plugins/define-plugin/#usage

    new webpack.DefinePlugin({
        PRODUCTION: JSON.stringify(true),
        VERSION: JSON.stringify("5fa3b9"),
        BROWSER_SUPPORTS_HTML5: true,
        TWO: "1+1",
        "typeof window": JSON.stringify("object")
    })
    

    With ESLint you need to specifically allow undefined variables in code, if you have no-undef rule on. http://eslint.org/docs/rules/no-undef like this:

    /*global TWO*/
    console.log('Running App version ' + TWO);
    

    EDIT 7th of Sep, 2017 (Create-React-App specific)

    If you're not into configuring too much, check out Create-React-App: Create-React-App - Adding Custom Environment Variables. Under the hood CRA uses Webpack anyway.

提交回复
热议问题