1.项目中我们经常要引用别人的包,很多时候我们使用的仅仅是别人包里面的几个方法或者样式,如果打包的时候将别人的包整个打包进行,就多了很多无用的代码,所以需要将这些无用的代码去掉。
2.去掉无用的js代码:这个功能webpack已经自带了,前提是我们要用es6的方式引用和导出包,并且打包的模式要为production生产模式。
3.去除无用的css代码:首先安装包:npm install purgecss-webpack-plugin -D
然后在webpack.config.js文件中使用该插件:
const{resolve,join}=require('path');//引入node中的join来合并两个路径
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const PurgecssPlugin = require('purgecss-webpack-plugin');//引入插件
const glob = require('glob');//引入node中的glob方法
const PATH = {src:join(__dirname,'src')}//拼接根路径
module.exports={
entry:{
vender:['./src/js/jquery.js','./src/js/common.js'],
index:'./src/js/index.js',
cart:'./src/js/cart.js'
},
output:{
path:resolve(__dirname,'build'),
filename:'[name].js'
},
mode:'development',
module:{
rules:[
//{test:/.css$/,use:['style-loader','css-loader']},
{test:/.css$/,use:[MiniCssExtractPlugin.loader,'css-loader','postcss-loader']},
{test:/.less$/,use:[MiniCssExtractPlugin.loader,'css-loader','less-loader','postcss-loader']},
{test:/.scss$/,use:[MiniCssExtractPlugin.loader,'css-loader','sass-loader','postcss-loader']},
{test:/.(jpg|png)$/,use:[{ loader:'url-loader',options:{
publichPath:'./images',
outputPath:'images/',
limit:1024*16,
name:'[name].[ext]'
}}]},
{test: /.(html)$/, use:['html-loader']},
{exclude:/.(js|json|html|css|less|scss|png|jpg|jpeg|gif)$/,use:[{loader:'file-loader',options:{
publichPath:'./svg',
outputPath:'svg/',
name:'[name].[ext]'
}}]},
{
test:/.js$/,
exclude:/node_modules/,
loader:'eslint-loader',
options:{
fix:true
}
}
]
},
plugins:[
new HtmlWebpackPlugin({
template:'./src/index.html',
filename:'index.html',
chunks:['vender','index']
}),
new HtmlWebpackPlugin({
template:'./src/cart.html',
filename:'cart.html',
chunks:['vender','cart']
}),
new MiniCssExtractPlugin({
filename:'index.css'
}),
//new OptimizeCssAssetsPlugin()
new PurgecssPlugin({//使用插件
paths:glob.sync(`${PATH.src}/**/*`,{nodir:true})//配置表是检查根路径下的所有文件中使用了的css文件才进行打包
})
],
target:"web",
devServer:{
port:3001,
compress:true,
open:true
}
}