tree shaking
目的:去除无用的代码
前提: JS 1. 必须使用ES6模块化 2. 开启production环境
作用: 减少代码体积
在 package.json中配置 “sideEffects: false” // 所有的代码中都没有副作用,都可以进行tree shaking
问题: 可能会把css/@babel/polyfill(副作用)文件干掉
“sideEffects”:[“.css”,”.less”] // 任意的css文件 (无副作用代码)
code split 代码分割
const HtmlWebpackPlugin = require(’html-webpack-plugin’)
module.exports = {
// 单入口 (单页面应用配置)
entry:’./src/js/index.js’,
// 多入口 :有一个入口,最终输出就有一个bundle (多页面应用配置)
entry {
main:’./src/js/index.js’,
test: ‘./src/js/test.js’
}
output: {
// [name]: 取文件名
filename: ‘js/[name].[contenthash:10].js’,
path: resovle(__dirname,’build’)
},
plugins: [
new HtmlWebpackPlugin({
template: ‘./src/index.html’,
minify: {
collapseWhitespace: true,
removeConmments: true
}
})
],
mode: ‘production’
}
const HtmlWebpackPlugin = require(’html-webpack-plugin’)
module.exports = {
entry:’./src/js/index.js’,
output: {
// [name]: 取文件名
filename: ‘js/[name].[contenthash:10].js’,
path: resovle(__dirname,’build’)
},
plugins: [
new HtmlWebpackPlugin({
template: ‘./src/index.html’,
minify: {
collapseWhitespace: true,
removeConmments: true
}
})
],
/
可以将node——modules中代码单独打包一个chunk最终输出
自动分析多入口chunk中,有没有公共的文件。如果有会打包为单独的chunk (chunk大小要求)
/
optimization: {
splitChuncks: {
chunks: ‘all’,
}
}
mode: ‘production’
}
const HtmlWebpackPlugin = require(’html-webpack-plugin’)
module.exports = {
entry:’./src/js/index.js’,
output: {
// [name]: 取文件名
filename: ‘js/[name].[contenthash:10].js’,
path: resovle(__dirname,’build’)
},
plugins: [
new HtmlWebpackPlugin({
template: ‘./src/index.html’,
minify: {
collapseWhitespace: true,
removeConmments: true
}
})
],
/
1.可以将node——modules中代码单独打包一个chunk最终输出
2.自动分析多入口chunk中,有没有公共的文件。如果有会打包为单独的chunk (chunk大小要求)
/
optimization: {
splitChuncks: {
chunks: ‘all’,
}
}
mode: ‘production’
}
index.js文件中
/
通过js代码,让某个文件单独打包成为一个chunk
import动态导入语法: 能将某个文件单独打包
/
import(/ webpackChunkname:’’test /‘./test’)
.then(()=> {
// 文件加载成功
console.log(resule);
})
.catch((error)=>{
// 文件加载失败
console.log(error);
})