为了建立一个新项目,我在我的配置文件中使用webpack 4.29.6
和webpack-dev-server 3.2.1
。我想添加HotModuleReplacementPlugin()
,但是当我执行npm run build或npm run dev时,它会抛出一个错误。
Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
- configuration.plugins[3] should be one of these:
object { apply, … } | function
-> Plugin of type object or instanceof Function
Details:
* configuration.plugins[3] should be an object.
-> Plugin instance
* configuration.plugins[3] should be an instance of function
-> Function acting as plugin
任何人都可以帮我解决这个问题吗?请注意,仅在模式生产时才应用插件。
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin(
Object.assign({}, {
inject: true,
template: publicDir + '/index.html',
},
isProduction ? {
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
} : undefined)),
isProduction &&
new MiniCssExtractPlugin({
filename: 'styles/[name].[contenthash:8].css',
chunkFilename: 'styles/[name].[contenthash:8].chunk.css',
}),
isDevelopment && new webpack.HotModuleReplacementPlugin(),
],
如果isProduction
或isDevelopment
不正确,则将其值作为插件传递。
你可以尝试这样的事情:
const PLUGINS = [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin(
Object.assign({}, {
inject: true,
template: publicDir + '/index.html',
},
isProduction ? {
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
} : undefined
)
),
];
if (isProduction) PLUGINS.push(
new MiniCssExtractPlugin({
filename: 'styles/[name].[contenthash:8].css',
chunkFilename: 'styles/[name].[contenthash:8].chunk.css',
})
);
if (isDevelopment) PLUGINS.push(
new webpack.HotModuleReplacementPlugin()
);
....
plugins: PLUGINS,
感谢@ UjinT34的建议,如果我的插件上的条件是假的,我突然不在数组中添加一个插件,而是一个布尔值。这就是为什么在插件数组的末尾我只需要过滤掉布尔值,就像那样:
plugins: [
...
isDevelopment && new webpack.HotModuleReplacementPlugin(),
].filter(Boolean),
...