在webpack中传递依赖于环境的变量 [英] Passing environment-dependent variables in webpack
问题描述
我正在尝试将一个角度应用程序从gulp转换为webpack。在gulp我使用gulp-preprocess来替换html页面中的一些变量(例如数据库名称),具体取决于NODE_ENV。使用webpack实现类似结果的最佳方法是什么?
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 NODE_ENV. What is the best way of achieving a similar result with webpack?
推荐答案
有两个基本的实现这一目标的方法。
There are two basic ways to achieve this.
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
}),
请注意,这只会按原样替换匹配项。这就是字符串的格式。你可以有一个更复杂的结构,比如那里有一个物体但是你明白了。
Note that this will just replace the matches "as is". That's why the string is in the format it is. You could have a more complex structure, such as an object there but you get the idea.
new webpack.EnvironmentPlugin(['NODE_ENV'])
EnvironmentPlugin
在内部使用 DefinePlugin
并通过它将环境值映射到代码。更简洁的语法。
EnvironmentPlugin
uses DefinePlugin
internally and maps the environment values to code through it. Terser syntax.
或者你可以通过别名模块。从消费者的角度来看,它看起来像这样:
Alternatively you could consume configuration through an aliased module. From consumer side it would look like this:
var config = require('config');
配置本身可能如下所示:
Configuration itself could look like this:
resolve: {
alias: {
config: path.join(__dirname, 'config', process.env.NODE_ENV)
}
}
假设 process.env。 NODE_ENV
是开发
。它将映射到 ./ config / development.js
然后。它映射到的模块可以导出如下配置:
Let's say process.env.NODE_ENV
is development
. It would map into ./config/development.js
then. The module it maps to can export configuration like this:
module.exports = {
testing: 'something',
...
};
这篇关于在webpack中传递依赖于环境的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!