Webpack - 需要基于构建配置的文件 [英] Webpack - Requiring a file based on build configuration
问题描述
在我们的项目中,可以在fake-backend 模式或real-backend 模式下运行应用程序.这个想法是,开发人员可以使用实现后端 API 但返回模拟数据的函数在本地进行开发.
In our project, it is possible to run the application in either fake-backend mode or real-backend mode. The idea is that the developer can develop locally with functions that implement backend API but return mock data.
我希望能够执行以下操作:
I'd like to be able to do something like:
webpack --config webpack-config-fake.js
然后在代码中我会做这样的事情:
Then in the code I would to do something like that:
var mockSuffix = webpackConfig.options.isFake ? "-fake" : "";
var backendApi = require('backend-api'+mockSuffix+'.js')
问题:
- 这听起来像是正确的做法吗?
- 如何访问源代码中使用的 webpackConfig?
- 我正在考虑的另一种方法是使用 Webpack 上下文.但是,我不确定它是否可以用来帮助这里.这是要考虑的事情吗?
推荐答案
在你的假"配置中,你可以通过NormalModuleReplacementPlugin代码>
.在以下示例中,require('backend-api')
产生 backend-api-mock
.
In your "fake" config, you could replace required modules via NormalModuleReplacementPlugin
. In the following example, require('backend-api')
yields backend-api-mock
.
plugins: [
new webpack.NormalModuleReplacementPlugin(/backend-api/, function(result) {
result.request = result.request.replace(/(backend-api)/, '$1-mock');
}),
],
您还可以指明在解决请求时您的模拟文件夹优先.请参阅resolve.root
.在下面的例子中,require('backend-api')
将首先查看 mockPath
并在没有找到相应的模块时回退到 dependenciesPath
.
You could also indicate that your mock folder takes precedence when resolving requests. See resolve.root
. In the following example, require('backend-api')
will first look into mockPath
and fall back to dependenciesPath
if no corresponding module was found.
resolve: {
root: [mockPath, dependenciesPath],
},
这篇关于Webpack - 需要基于构建配置的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!