我正在尝试将一个angular应用程序从gulp转换为webpack。在gulp中,我使用gulp预处理来替换html页面中的一些变量(例如数据库名称),这取决于NODE_ENV。用webpack实现类似结果的最佳方法是什么?


当前回答

这是另一个类似于@zer0chain的答案的答案。但是,有一个区别。

设置webpack -p就足够了。

即:

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

这就等于

// webpack.config.js
const webpack = require('webpack');

module.exports = {
  //...

  plugins:[
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('production')
    })
  ]
};

所以你可能只需要打包这样的东西。json节点文件:

{
  "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",
    ...
  }
}

下面是一些来自DefinePlugin的提示:

DefinePlugin允许您创建可以在编译时配置的全局常量。这对于允许开发构建和发布构建之间的不同行为是有用的。例如,您可以使用一个全局常量来确定是否进行日志记录;也许您在开发构建中执行日志记录,但在发布构建中不执行。这就是DefinePlugin所促进的那种场景。


这样你就可以检查你是否输入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]

其他回答

有两种基本方法可以实现这一点。

DefinePlugin

new webpack.DefinePlugin({
    'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
}),

注意,这将只是替换匹配的“原样”。这就是为什么字符串是这样的格式。你可以有一个更复杂的结构,比如一个物体但你懂的。

EnvironmentPlugin

new webpack.EnvironmentPlugin(['NODE_ENV'])

EnvironmentPlugin在内部使用DefinePlugin并通过它将环境值映射到代码。含混的语法。

别名

或者,您可以通过别名模块使用配置。从消费者的角度来看,它是这样的:

var config = require('config');

配置本身可能是这样的:

resolve: {
    alias: {
        config: path.join(__dirname, 'config', process.env.NODE_ENV)
    }
}

我们写入process。env。NODE_ENV是开发。然后它会映射到。/config/development.js。它映射到的模块可以像这样导出配置:

module.exports = {
    testing: 'something',
    ...
};

现在2020年,我也面临着同样的问题,但是对于这个老问题,有很多新的答案,就列举一些吧:

这是webpack.config.js

plugins: [
        new HtmlWebpackPlugin({
            // 1. title is the parameter, you can use in ejs template
            templateParameters:{
                title: JSON.stringify(someting: 'something'),
            },
        }), 


        //2. BUILT_AT is a parameter too. can use it.
        new webpack.DefinePlugin({
            BUILT_AT: webpack.DefinePlugin.runtimeValue(Date.now,"some"),

        }),

        //3. for webpack5, you can use global variable: __webpack_hash__
        //new webpack.ExtendedAPIPlugin()
    ],
    //4. this is not variable, this is module, so use 'import tt' to use it.
    externals: { 
        'ex_title': JSON.stringify({
            tt: 'eitentitle',
        })
    },

这4种方法只是基本的,我相信还有更多的方法。但我认为这是最简单的方法。

我研究了几个关于如何设置特定于环境的变量的选项,最后得到了这样的结果:

我目前有2个webpack配置:

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')
  }
}),

在我的代码中,我以这种(简要)方式获取API_URL的值:

统一文件格式

编辑2016年11月3日

Webpack文档有一个例子: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")
})

使用ESLint,如果你有no-undef规则,你需要在代码中明确地允许未定义的变量。http://eslint.org/docs/rules/no-undef像这样:

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

EDIT 2017年9月7日(Create-React-App特定)

如果您不喜欢配置太多,请查看Create-React-App: Create-React-App -添加自定义环境变量。实际上CRA使用Webpack。

因为我在上面的帖子上的编辑没有被批准,所以发布了额外的信息。

如果你想从包装中挑选价值。类似于定义的版本号,并通过Javascript中的DefinePlugin访问它。

{"version": "0.0.1"}

然后,导入包。Json在各自的webpack中。config,使用import变量访问该属性,然后在DefinePlugin中使用该属性。

const PACKAGE = require('../package.json');
const _version = PACKAGE.version;//Picks the version number from package.json

例如,webpack上的某些配置。config为DefinePlugin使用元数据:

const METADATA = webpackMerge(commonConfig({env: ENV}).metadata, {
  host: HOST,
  port: PORT,
  ENV: ENV,
  HMR: HMR,
  RELEASE_VERSION:_version//Version attribute retrieved from package.json
});

new DefinePlugin({
        'ENV': JSON.stringify(METADATA.ENV),
        'HMR': METADATA.HMR,
        'process.env': {
          'ENV': JSON.stringify(METADATA.ENV),
          'NODE_ENV': JSON.stringify(METADATA.ENV),
          'HMR': METADATA.HMR,
          'VERSION': JSON.stringify(METADATA.RELEASE_VERSION)//Setting it for the Scripts usage.
        }
      }),

在任何typescript文件中访问它:

this.versionNumber = process.env.VERSION;

最聪明的方法是这样的:

// webpack.config.js
plugins: [
    new webpack.DefinePlugin({
      VERSION: JSON.stringify(require("./package.json").version)
    })
  ]

感谢罗斯·艾伦

你可以使用——env传递环境变量,而不需要额外的插件

Webpack -

webpack --config webpack.config.js --env.foo=bar

Webpack 5+(无)

webpack --config webpack.config.js --env foo=bar

然后,使用webpack.config.js中的变量:

module.exports = function(env) {
    if (env.foo === 'bar') {
        // do something
    }
}

进一步阅读:Webpack 2.0不支持自定义命令行参数? # 2254