Webpack5打包时遇见模板文件index.html冲突
问题描述
事情是这样的,最近这在自行搭建react加typescript开发环境,使用到的webpack版本是5.75.0
。前面的步骤还是没有什么问题的,区分了开发与生产环境,但是之后在public文件下公共静态资源的打包时遇见了一个问题,public文件夹下面的favicon.ico
文件并没有打包到指定的打包路径,因此想到了使用webpack插件copy-webpack-plugin
进行静态资源的复制,这一部分插件的配置是在webpack.common.js
中。原本按照设想是没有问题的,但是,实际上却出问题了。以下为报错提示:
ERROR in ./src/index.tsx
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Unknown option: .plungins. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options.
at validate (H:\vscodeworkstation\react_app\lush-blog-frontend\node_modules\@babel\core\lib\config\validation\options.js:86:25)
at H:\vscodeworkstation\react_app\lush-blog-frontend\node_modules\@babel\core\lib\config\config-chain.js:170:34
at cachedFunction (H:\vscodeworkstation\react_app\lush-blog-frontend\node_modules\@babel\core\lib\config\caching.js:48:27)
at cachedFunction.next (<anonymous>)
at evaluateSync (H:\vscodeworkstation\react_app\lush-blog-frontend\node_modules\gensync\index.js:251:28)
at sync (H:\vscodeworkstation\react_app\lush-blog-frontend\node_modules\gensync\index.js:89:14)
at buildRootChain (H:\vscodeworkstation\react_app\lush-blog-frontend\node_modules\@babel\core\lib\config\config-chain.js:107:31)
at buildRootChain.next (<anonymous>)
at loadPrivatePartialConfig (H:\vscodeworkstation\react_app\lush-blog-frontend\node_modules\@babel\core\lib\config\partial.js:79:62)
at loadPrivatePartialConfig.next (<anonymous>)
ERROR in Conflict: Multiple assets emit different content to the same filename index.html
前置分析
下面贴出部分我认为有问题的webpack配置
module.exports = {
// 其他配置
plugins: [
new HtmlWebpackPlugin({
template: resolve(PROJECT_PATH, './public/index.html'),
filename: 'index.html',
cache: false,
minify: isDev
? false
: {
removeAttributeQuotes: true,
collapseWhitespace: true,
removeComments: true,
collapseBooleanAttributes: true,
collapseInlineTagWhitespace: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
minifyCSS: true,
minifyJS: true,
minifyURLs: true,
useShortDoctype: true,
},
}),
new CopyPlugin({
patterns: [
{
context: resolve(PROJECT_PATH, './public'),
from: '*',
to: resolve(PROJECT_PATH, './dist'),
toType: 'dir',
},
],
}),
],
}
按照报错分析,应该是在进行打包的过程中,有多个插件尝试修改index.html,导致了冲突发生。对于html-webpack-plugin
来说,会将打包后的js文件引入到index.html中并输出到打包路径dist
,同时对于copy-webpack-plugin
来说,其同时复制了public下面的index.html到打包路径下,这样就产生了冲突。
笔者前端开发掌握的不太好,对于插件`copy-webpack-plugin`不太熟悉,望在座各位能够不吝赐教