Passing environment-dependent variables in webpack

后端 未结 15 1923
醉酒成梦
醉酒成梦 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:26

    I'm not a huge fan of...

    new webpack.DefinePlugin({
      'process.env': envVars
    }),
    

    ...as it does not provides any type of security. instead, you end up boosting your secret stuff, unless you add a webpack to gitignore

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 13:29

    Just another answer that is similar to @zer0chain's answer. However, with one distinction.

    Setting webpack -p is sufficient.

    It is the same as:

    --define process.env.NODE_ENV="production"
    

    And this is the same as

    // webpack.config.js
    const webpack = require('webpack');
    
    module.exports = {
      //...
    
      plugins:[
        new webpack.DefinePlugin({
          'process.env.NODE_ENV': JSON.stringify('production')
        })
      ]
    };
    

    So you may only need something like this in package.json Node file:

    {
      "name": "projectname",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "debug": "webpack -d",
        "production": "webpack -p"
      },
      "author": "prosti",
      "license": "ISC",
      "dependencies": {    
        "webpack": "^2.2.1",
        ...
      }
    }
    

    Just a few tips from the DefinePlugin:

    The DefinePlugin allows you to create global constants which can be configured at compile time. This can be useful for allowing different behavior between development builds and release builds. For example, you might use a global constant to determine whether logging takes place; perhaps you perform logging in your development build but not in the release build. That's the sort of scenario the DefinePlugin facilitates.


    That this is so you can check if you type webpack --help

    Config options:
      --config  Path to the config file
                             [string] [default: webpack.config.js or webpackfile.js]
      --env     Enviroment passed to the config, when it is a function
    
    Basic options:
      --context    The root directory for resolving entry point and stats
                                           [string] [default: The current directory]
      --entry      The entry point                                          [string]
      --watch, -w  Watch the filesystem for changes                        [boolean]
      --debug      Switch loaders to debug mode                            [boolean]
      --devtool    Enable devtool for better debugging experience (Example:
                   --devtool eval-cheap-module-source-map)                  [string]
      -d           shortcut for --debug --devtool eval-cheap-module-source-map
                   --output-pathinfo                                       [boolean]
      -p           shortcut for --optimize-minimize --define
                   process.env.NODE_ENV="production" 
    
                          [boolean]
      --progress   Print compilation progress in percentage                [boolean]
    
    0 讨论(0)
提交回复
热议问题