[英]Using webpack-merge to prepend loaders to a rules `use` array
I use webpack-merge to merge my webpack config files for dev and prod environments.我使用webpack-merge为开发和生产环境合并我的 webpack 配置文件。 To extract CSS in prod mode, I use the mini-css-extract-plugin .
要在 prod 模式下提取 CSS,我使用mini-css-extract-plugin 。 According to its documentation, I use it in place of the
style-loader
, which is only used during development.根据它的文档,我用它来代替
style-loader
,它只在开发期间使用。 At this moment, my webpack config for CSS blocks looks like this:此时,我的 CSS 块的 webpack 配置如下所示:
// webpack.common.js
{
test: /\.(sa|sc|c)ss$/,
use: [
process.env.NODE_ENV === `production` ? MiniCssExtractPlugin.loader : `style-loader`,
`css-loader`,
`postcss-loader`,
`sass-loader`
]
}
This works, but since I am using webpack-merge
, I want to avoid this kind of logic in my common config file.这可行,但是由于我使用的是
webpack-merge
,因此我想在我的常用配置文件中避免这种逻辑。 Now, I have tried to split this up like so and have webpack-merge
merge the various loaders:现在,我尝试像这样拆分它并让
webpack-merge
合并各种加载器:
// webpack.common.js
{
test: /\.(sa|sc|c)ss$/,
use: [
`css-loader`,
`postcss-loader`,
`sass-loader`
]
}
// webpack.dev.js
{
test: /\.(sa|sc|c)ss$/,
use: [
`style-loader`,
// webpack-merge should prepend all loaders from `webpack.common.js`
]
}
// webpack.prod.js
{
test: /\.(sa|sc|c)ss$/,
use: [
MiniCssExtractPlugin.loader,
// webpack-merge should prepend all loaders from `webpack.common.js`
]
}
Using the basic merge
fn, the use
arrays doesnt get merged, but replaced, which ofc leads to an error: ModuleParseError: Module parse failed: You may need an appropriate loader to handle this file type.
使用基本的
merge
fn, use
arrays 不会被合并,而是被替换,这会导致错误: ModuleParseError: Module parse failed: You may need an appropriate loader to handle this file type.
So I tried to use merge.smartStrategy({ 'module.rules.use': 'prepend' })()
, but I get an error: TypeError: this[MODULE_TYPE] is not a function
.所以我尝试使用
merge.smartStrategy({ 'module.rules.use': 'prepend' })()
,但出现错误: TypeError: this[MODULE_TYPE] is not a function
。 Is there something I am missing or is this simply not possible?有什么我想念的,或者这根本不可能吗?
While splitting up my webpack config, I have forgotten to include the MiniCssExtractPlugin
in the plugins
section of my prod. 在拆分我的webpack配置时,我忘记将
MiniCssExtractPlugin
包括在产品的plugins
部分中。 config file. 配置文件。
Everything works as expected using merge.smartStrategy({ 'module.rules.use': 'prepend' })()
. 使用
merge.smartStrategy({ 'module.rules.use': 'prepend' })()
一切都会按预期进行。
it's a little update.这是一个小更新。 In modern versions of webpack you should use mergeWithRules.
在 webpack 的现代版本中,您应该使用 mergeWithRules。 In that case it looks like this
在这种情况下,它看起来像这样
// webpack.common.js
{
test: /\.(sa|sc|c)ss$/,
use: [
`postcss-loader`,
`sass-loader`
]
}
// webpack.dev.js
{
test: /\.(sa|sc|c)ss$/,
use: [
"style-loader"
]
}
mergeWithRules({
module: {
rules: {
test: "match",
use: "prepend",
},
},
})(common, dev);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.