plugins其实就是webpack的插件,使用这些插件使得webpack变得更加灵活.(https://webpack.js.org/plugins/
)
html-webpack-plugin
html-webpack-plugin的主要作用就是简化了html文件的创建,方便webpack打包
官网介绍https://webpack.js.org/plugins/html-webpack-plugin/
1.安装:
npm install --save-dev html-webpack-plugin
2.配置webpack.config.js
//引入
const HtmlWebpackPlugin=require('html-webpack-plugin');
//配置plugins
plugins:[new HtmlWebpackPlugin({
template:'./index.html'
})]
完整的配置文件(包含了CleanWebpackPlugin)
const path=require('path');
const HtmlWebpackPlugin=require('html-webpack-plugin');
const {CleanWebpackPlugin}= require('clean-webpack-plugin');
module.exports={
mode:'development',
entry:{
main:'./index.js'
},
module:{
rules:[
{
test:/\.jpg$/,
use:{
loader:'file-loader',
options:{
outputPath:'images',
name:'img.jpg'
}
}
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},{
test: /\.scss$/,
use: [
"style-loader", // creates style nodes from JS strings
"css-loader", // translates CSS into CommonJS
"sass-loader" // compiles Sass to CSS, using Node Sass by default
]
}
]
},
output:{
path:path.resolve(__dirname,'./dist'),
filename:'index_bundle.js'
},
plugins:[new HtmlWebpackPlugin({
template:'./index.html'
}),new CleanWebpackPlugin()]
}
3.说明:在使用html-webpack-plugin中如果你不配置template,那么它会默认生成一个index.html页面并且引入了你已经打包的js(我这里是index_bundle.js),你配置template那么它就会按照你指定的模板页面进行生成html
我的模板页面如下:
CleanWebpackPlugin
clean-webpack-plugin是一个三方的插件现在还没纳入webpack的官网详细信息看https://github.com/johnagan/clean-webpack-plugin
主要的作用就是删除上一次打包好的文件
2.1安装:
npm install --save-dev clean-webpack-plugin
2.2webpack.config.js配置:
//1引入
const {CleanWebpackPlugin}= require('clean-webpack-plugin');
//2配置CleanWebpackPlugin
plugins:[new CleanWebpackPlugin()]
2.3完整的webpack.config.js:
const path=require('path');
const HtmlWebpackPlugin=require('html-webpack-plugin');
const {CleanWebpackPlugin}= require('clean-webpack-plugin');
module.exports={
mode:'development',
entry:{
main:'./index.js'
},
module:{
rules:[
{
test:/\.jpg$/,
use:{
loader:'file-loader',
options:{
outputPath:'images',
name:'img.jpg'
}
}
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},{
test: /\.scss$/,
use: [
"style-loader", // creates style nodes from JS strings
"css-loader", // translates CSS into CommonJS
"sass-loader" // compiles Sass to CSS, using Node Sass by default
]
}
]
},
output:{
path:path.resolve(__dirname,'./dist'),
filename:'index_bundle.js'
},
plugins:[new HtmlWebpackPlugin({
template:'./index.html'
}),new CleanWebpackPlugin()]
}
更多关于plugins的知识看官网:https://webpack.js.org/plugins/