问题描述
我有一些东西需要开发 - 例如,我不想用它来膨胀我的分布式构建文件的模拟.
I have some things for development - e.g mocks which I would like to not bloat my distributed build file with.
在 RequireJS 中,你可以在插件文件中传递一个配置,并根据它有条件地要求内容.
In RequireJS you can pass a config in a plugin file and conditonally require things in based on that.
对于 webpack,似乎没有办法做到这一点.首先为我使用的环境创建运行时配置 resolve.alias 重新指向一个 require 依赖关于环境,例如:
For webpack there doesn't seem to be a way of doing this. Firstly to create a runtime config for an environment I have used resolve.alias to repoint a require depending on the environment, e.g:
// All settings.
var all = {
fish: 'salmon'
};
// `envsettings` is an alias resolved at build time.
module.exports = Object.assign(all, require('envsettings'));
然后在创建 webpack 配置时,我可以动态分配 envsettings
指向的文件(即 webpackConfig.resolve.alias.envsettings = './' + env
).
Then when creating the webpack config I can dynamically assign which file envsettings
points to (i.e. webpackConfig.resolve.alias.envsettings = './' + env
).
但是我想做类似的事情:
However I would like to do something like:
if (settings.mock) {
// Short-circuit ajax calls.
// Require in all the mock modules.
}
但显然,如果环境不是模拟的,我不想构建那些模拟文件.
But obviously I don't want to build in those mock files if the environment isn't mock.
我可以再次使用 resolve.alias 手动将所有这些要求重新指向存根文件 - 但有没有一种感觉不那么讨厌的方法?
I could possibly manually repoint all those requires to a stub file using resolve.alias again - but is there a way that feels less hacky?
任何想法我怎么能做到这一点?谢谢.
Any ideas how I can do that? Thanks.
推荐答案
您可以使用 define插件.
我通过在你的 webpack 构建文件中做一些像这样简单的事情来使用它,其中 env
是导出设置对象的文件的路径:
I use it by doing something as simple as this in your webpack build file where env
is the path to a file that exports an object of settings:
// Webpack build config
plugins: [
new webpack.DefinePlugin({
ENV: require(path.join(__dirname, './path-to-env-files/', env))
})
]
// Settings file located at `path-to-env-files/dev.js`
module.exports = { debug: true };
然后在你的代码中
if (ENV.debug) {
console.log('Yo!');
}
如果条件为假,它将从您的构建文件中删除此代码.您可以在 此处查看 Webpack 构建示例.
It will strip this code out of your build file if the condition is false. You can see a working Webpack build example here.
这篇关于使用 Webpack 基于环境条件构建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!