學習npm包請一定先去npm官方看一下文檔介紹,實在不行再去看別人的解說,自己能搞懂是最好的。
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
mode:"development",
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
module:{
noParse: /jquery|lodash/,
//noParse: (content) => /jquery|lodash/.test(content),
unsafeCache:true, // webpack4 默認為true
rules:[
{
test:/\.css$/,
use:[
'style-loader',
'css-loader'
]
},
{
test:/\.(png|svg|jpg|gif)$/,
use:[
{
loader:'file-loader',
options:{
outputPath:'/images',
}
}
]
},
{
test:/\.(woff|woff2|eot|ttf|otf)$/,
use:[
{
loader:'file-loader',
options:{
outputPath:'/font',
}
}
]
},
{
test:/\.xml$/,
use:[
'xml-loader'
]
}
],
},
plugins:[
new HtmlWebpackPlugin({
template:'./src/index.html'
}),
]
};
簡單來說html-webpack-plugin就是生成一個html文件,可以是無配置的,無配置的情況它可以自動生成一個html,內容如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Webpack App</title>
</head>
<body>
<script src="index_bundle.js"></script>
</body>
</html>
<script src="bundle.js"></script> 是把默認bundle.js引入的,但是很多情況下我們的index.html可能有一些特殊的內容,這樣默認的配置不能滿足,這時候html-webpack-plugin的配置項就會起作用,最經常使用的就是 template:'你的html的路徑'.
另一個經常出現(xiàn)的問題的 title:'titleName' 明明配置了,但是生成的html里title卻不會改變,認真看官方文檔,依據(jù)template的html文件里<title><%= htmlWebpackPlugin.options.title %></title> 這樣寫才可以,其實很多問題看官方說明足以解決了,我們要找到學習的方法。
另外一個經常使用的plugin是clean-webpack-plugin,它的作用是每次build時把 output.path 文件夾下的內容清除掉。
npm install --save-dev clean-webpack-plugin 簡寫:npm install -D clean-webpack-plugin
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const webpackConfig = {
plugins: [
new CleanWebpackPlugin(),
],
};
module.exports = webpackConfig;
最后多說一些 : -S 生產 -D 是開發(fā) 一個包是裝開發(fā)還是生產要看最終上生產時是否會用到包的內容,以react項目舉個例子:
react,react-dom包肯定是生產用,如果用了antd那也裝生產-S;而eslint,babel,各種loader,各種plugins基本都是build時發(fā)揮作用,生成最終文件時就不需要它們了,所以裝-D .