在 webpack 中传递环境相关变量 [英] Passing environment-dependent variables in webpack

查看:22
本文介绍了在 webpack 中传递环境相关变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 angular 应用程序从 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_ENVdevelopment.然后它会映射到 ./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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆