基于使用的WebPack环境条件建设 [英] Conditional build based on environment using Webpack
问题描述
我有一些事情的发展 - 例如嘲笑我想不膨胀我的分布式构建文件,
I have some things for development - e.g mocks which I would like to not bloat my distributed build file with.
在RequireJS你可以在一个插件文件传递配置和基于conditonally需要的东西。
In RequireJS you can pass a config in a plugin file and conditonally require things in based on that.
有关的WebPack似乎没有被这样的一种方式。首先创建我已经使用 resolve.alias 以重新指向的环境中运行时的配置取决于一个要求对环境,例如:
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
)。
不过,我想这样做是这样的:
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.
推荐答案
您可以使用href=\"https://github.com/webpack/docs/wiki/list-of-plugins#defineplugin\">定义。
You can use the define plugin.
我在你的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 };
和那么这在code
if (ENV.debug) {
console.log('Yo!');
}
如果条件为假它将剥离这种code你的构建文件。你可以看到一个工作<一个href=\"https://github.com/mderrick/webpack-react-boilerplate/blob/master/webpack.default.config.js#L74\">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环境条件建设的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!