我正在尝试将一个angular应用程序从gulp转换为webpack。在gulp中,我使用gulp预处理来替换html页面中的一些变量(例如数据库名称),这取决于NODE_ENV。用webpack实现类似结果的最佳方法是什么?
当前回答
现在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种方法只是基本的,我相信还有更多的方法。但我认为这是最简单的方法。
其他回答
你可以使用——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
这里有一种方法,对我来说是有效的,并允许我通过重用json文件保持我的环境变量DRY。
const webpack = require('webpack');
let config = require('./settings.json');
if (__PROD__) {
config = require('./settings-prod.json');
}
const envVars = {};
Object.keys(config).forEach((key) => {
envVars[key] = JSON.stringify(config[key]);
});
new webpack.DefinePlugin({
'process.env': envVars
}),
dotenv-webpack
一个安全的webpack插件,支持dotenv和其他环境变量,只公开您选择和使用的内容。
通过一些基于默认选项的配置解决方案来实现这一点,一旦包有.env.defaults文件作为env变量的初始值,您就可以在开发中使用它,并让.env用于生产。
使用
安装包
npm install dotenv-webpack --save-dev
创建一个.env.defaults文件
API_URL='dev_url/api/'
创建一个.env文件,保留它为空,使用默认值,在部署过程中更新它 配置webpack - webpack. Config .js
new Dotenv({
defaults: true
})
开发环境测试文件。js
console.log(process.env.API_URL)
// Outputs: dev_url/api/
在构建时,更新空的.env文件
API_URL='prod_url/api/'
Dotenv-webpack将使用这个来覆盖env.defaults
产品环境测试文件。js
console.log(process.env.API_URL)
// Outputs: prod_url/api/
dotenv-webpack dotenv-defaults
现在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种方法只是基本的,我相信还有更多的方法。但我认为这是最简单的方法。
就我个人而言,我更喜欢以下这些答案:
const webpack = require('webpack');
const prod = process.argv.indexOf('-p') !== -1;
module.exports = {
...
plugins: [
new webpack.DefinePlugin({
process: {
env: {
NODE_ENV: prod? `"production"`: '"development"'
}
}
}),
...
]
};
使用它不会有奇怪的env变量或跨平台问题(使用env变量)。你所要做的就是分别为开发或生产运行普通的webpack或webpack -p。
参考:Github问题