CleanWebpackPlugin
使用CleanWebpackPlugin可以在構建的時候自動清除之前構建殘留的dist目錄中的內容,避免手動操作。
安裝
npm install clean-webpack-plugin --save-dev
使用
# webpack.config.js
# 需要注意的是,CleanWebpackPlugin在引入時需要解構
const {CleanWebpackPlugin} = require('clean-webpack-plugin')
module.exports = {
plugins: [
new CleanWebpackPlugin()
]
}
CleanWebpackPlugin默認會去清除dist目錄下的內容,當然CleanWebpackPlugin還支持很多設置項,暫時沒有用到,不做深入研究了。
HtmlWebpackPlugin
HtmlWebpackPlugin可以爲我們動態生成index.html,當構建的js使用了chunkhash這些動態的值避免緩存時,HtmlWebpackPlugin會動態地爲我們引入每次生成的最新的js,從而避免手動去管理index.html。
安裝
npm install html-webpack-plugin --save-dev
使用
# webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
plugins: [
new HtmlWebpackPlugin({
# 使用template指定的模板,生成的index.html就是參照模板來的
template: 'index.ejs',
# 向模板中傳遞參數
title: '沒錯,我就是標題'
})
]
}
<!--index.ejs-->
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="utf-8">
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<div id="app"></div>
</body>
</html>
<!--構建生成的index.html,默認放在dist目錄下-->
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="utf-8">
<title>沒錯,我就是標題</title>
</head>
<body>
<div id="app"></div>
<script type="text/javascript" src="dist/build-05a85e5c705d85ed3aa5.js"></script>
</body>
</html>
webpack項目中插件形式引入Jquery
安裝Jquery
npm install jquery --save
引入及使用
# webpack.config.js
# 將jquery設置爲可用的插件,設置後全局可引用,這樣設置使用$和JQuery都可以使用jquery
module.exports = {
plugins: [
new webpack.ProvidePlugin({
jQuery: "jquery",
$: "jquery"
}),
]
}
# 在js中直接使用上述引入的插件即可,$與jQuery都可以
$.ajax({
type: 'POST',
url: url,
data: sendData,
contentType: 'application/json; charset=UTF-8',
dataType: 'json',
error: errorFunction
}).then(thenSucHandler, thenFialHandler)
.then((data) => {
return data;
})
jQuery.ajax({
type: 'POST',
url: url,
data: sendData,
contentType: 'application/json; charset=UTF-8',
dataType: 'json',
error: errorFunction
}).then(thenSucHandler, thenFialHandler)
.then((data) => {
return data;
})