前端頁面基礎資源
有些頁面使用的基礎庫是一樣的,並且也有公共的模塊
對於這些資源如果打包的時候每個都打一份,會導致打包的體積比較大
webpack提取頁面公共資源,比如公共包,公共模塊?
webpack 提取頁面公共資源
基礎庫分離
思路: 將react、react-dom通過cdn引入,不打入bundle中
方法: 1. 使用html-webpack-externals-plugin 2. 使用splitChunks
splitChunks
webpakc4內置的,替代commonChunkPlugin插件(webpack3常用),功能非常強大,做代碼分割基本上離不開這個庫
chunks參數說明
async:異步引入的庫進行分離(默認,只分析異步、動態引入的庫)
initial: 同步引入的庫進行分離(同步的就分離)
all: 所有引入的庫進行分離(推薦,不論同步、異步都提取)
默認參數
module.exports = {
optimizatin:{
splitChunks:{
chunks:'async', // 需要分離哪些庫
minSize:30000, // 抽離公共包最小的大小,30k
maxSize:0, // 最大的大小,單位是字節
minChunks:1, // 最小引用的次數,比如一個方法在多個頁面都使用到
maxAsyncRequests:5, // 瀏覽器每次請求異步資源的次數.通過插件分離出的庫被同時請求的數量
maxInitialRequests:3,
automaticNameDelimiter:'~',
name:true,
cacheGroups:{
vendors:{
test:/[\\/]node_modules[\\/]/, // 匹配出要分離的包
priority:-10
}
}
}
}
}
提取公共包 HtmlWebpackExternalsPlugin方式
安裝
npm i html-webpack-externals-plugin@3.8.0 -D
配置HtmlWebpackExternalsPlugin
module.exports = {
plugins:[
new HtmlWebpackExternalsPlugin({
{
module:'react',
entry:'https://now8.gtimg.com/now/lib/16.8.6/react.min.js',
global:'React'
},
{
module:'react-dom',
entry:'https://now8.gtimg.com/now/lib/16.8.6/react-dom.min.js',
global:'ReactDom'
}
})
]
}
最后在index.html模板頁面引入cdn腳本
splitChunks方式
對於多頁面應用,如果不提取公共庫,那么每個頁面都會把公共包打包進去,造成bunlde體積冗余
可以使用splitChunks將公共庫提取出來, 需要的頁面都使用同一個包
- 分離公共庫配置
module.exports = {
optimization:{
splitChunks:{
cacheGroups:{
commons:{
test:/(react)|(react-dom)/, // 匹配
name:'vendors', // 將react和react-dom提取出來叫vendors
chunks:'all'
}
}
}
}
}
分離之前
可以看到comp1 和 comp 因為都將react打包引入了,導致兩個包都有100多K
Asset Size Chunks Chunk Names
comp.html 2.88 KiB [emitted]
comp1.html 2.89 KiB [emitted]
comp1_2174f810.css 126 bytes 1 [emitted] comp1
comp1_80beb5fc.js 119 KiB 1 [emitted] comp1
comp_2174f810.css 126 bytes 0 [emitted] comp
comp_a0497db7.js 119 KiB 0 [emitted] comp
dalao_982163fc.jpg 35.8 KiB [emitted]
helloworld.html 298 bytes [emitted]
helloworld_06fed627.js 1000 bytes 2 [emitted] helloworld
分離之后
此時react/react-dom已經被提取成vendors,comp和comp1僅有9.45kb,大大優化了打包體積
Asset Size Chunks Chunk Names
comp.html 2.95 KiB [emitted]
comp1.html 2.95 KiB [emitted]
comp1_e1399198.js 9.45 KiB 2 [emitted] comp1
comp_f76b4f2b.js 9.45 KiB 1 [emitted] comp
dalao_982163fc.jpg 35.8 KiB [emitted]
helloworld.html 415 bytes [emitted]
helloworld_149cdeea.js 1000 bytes 3 [emitted] helloworld
vendors_6d383d43.css 126 bytes 0 [emitted] vendors
vendors_898437c4.js 110 KiB 0 [emitted] vendors
要使用vendors的話需要在HtmlWebackPlugin中chunks加入'vendors'
{
chunks:['vendors',pageName]
}
- 提取公共方法配置
分別minSize設置0和1000k大小
minchunks為三次
同時修改HtmlWebpackPlugin的chunks屬性
module.exports = {
optimization: {
splitChunks: {
minSize:0, // 最小為0kb
cacheGroups: {
commons: {
name: 'commons', // 對應htmlwebpackplugin中添加的chunk name
chunks: 'all',
minChunks: 2, // 最小引用次數
}
}
}
}
}
完整配置
'use strict';
const path = require('path');
const glob = require('glob')
// 將css commonjs 抽成css文件
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
// 壓縮css文件
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin')
// 壓縮html,有幾個入口就對應幾個html
const HtmlWebpackPlugin = require('html-webpack-plugin')
// 每次構建的時候自動清除之前的dist目錄下的文件
const CleanWebpackPlugin = require('clean-webpack-plugin')
const setMPA = () => {
const entry = {}
const HtmlWebpackPlugins = []
const entryFiles = glob.sync(path.join(__dirname, './src/*/index.js'))
Object.keys(entryFiles).map(index => {
const entryFile = entryFiles[index]
const match = entryFile.match(/src\/(.*)\/index\.js/)
const pageName = match && match[1]
entry[pageName] = `./src/${pageName}/index.js`
HtmlWebpackPlugins.push(new HtmlWebpackPlugin({
// html模板所在路徑
template: path.join(__dirname, `src/${pageName}/index.html`),
// 指定輸出文件名稱
filename: `${pageName}.html`,
// 使用哪個chunk生成html頁面
chunks: ['commons', pageName],
// 為true時,js\css\會自動注入此html中來
inject: true,
// 處理換行,空格,注釋
minify: {
html5: true,
collapseWhitespace: true,
preserveLineBreaks: false,
minifyCSS: true,
minifyJS: true,
removeComments: false
}
}))
})
return {
entry,
HtmlWebpackPlugins
}
}
const { entry, HtmlWebpackPlugins } = setMPA()
module.exports = {
// 生產模式還是開發模式
mode: 'production',
// 入口 指定入口文件
entry,
// 出口
output: {
// 指定輸出目錄
path: path.join(__dirname, 'dist'),
filename: '[name]_[chunkhash:8].js'
},
// 配置loader
module: {
rules: [
{
test: /.js$/,
use: 'babel-loader'
},
{
test: /.css$/,
use: [
MiniCssExtractPlugin.loader,
// 'style-loader', // 再將樣式插入到style標簽中
'css-loader' // 將css轉換成commonjs
]
},
{
test: /.less$/,
use: [
MiniCssExtractPlugin.loader,
// 'style-loader', // 再將樣式插入到style標簽中
'css-loader', // 將css轉換成commonjs
'less-loader', // 將less文件轉換成css文件
// 自動補齊css3前綴
{
loader: 'postcss-loader',
options: {
plugins: () => [
require('autoprefixer')(
{ browsers: ['last 2 version', '>1%', 'ios 7'] }
)
]
}
},
// px2rem-loader 移動端適配
{
loader: 'px2rem-loader',
options: {
remUnit: 75, // 1rem對應75px,10rem對應750px,適合750px視覺稿
remPrecision: 8 // px轉rem后,小數點的位數
}
}
]
},
{
test: /\.(png|jpg|gif|jpeg)$/,
use: [
{
loader: 'file-loader',
// 圖片指紋
options: {
name: '[name]_[hash:8].[ext]'
}
// loader: 'url-loader',
// options: {
// limit: 40 * 1024 // 40k
// }
}
]
},
{
test: /\.(woff|woff2|eot|ttf|otf|otf)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name]_[hash:8].[ext]'
}
}
]
}
]
},
plugins: [
// css使用contenthash,避免css沒變js變化的時候,css的hash值頁隨着發布一起變化
new MiniCssExtractPlugin({
filename: '[name]_[contenthash:8].css',
}),
// 壓縮css文件
new OptimizeCssAssetsPlugin({
assetNameRegExp: /\.css$/g,
// css預處理器
cssProcessor: require('cssnano')
}),
// 自動清除dist目錄下的文件
new CleanWebpackPlugin()
].concat(HtmlWebpackPlugins), // 壓縮html
optimization: {
splitChunks: {
minSize: 0,
cacheGroups: {
commons: {
name: 'commons',
chunks: 'all',
minChunks: 2,
}
}
}
}
}
json
{
"name": "02beginning",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": " webpack --config webpack.prod.js",
"watch": "webpack --watch",
"dev": "webpack-dev-server --config webpack.dev.js --open"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.4.4",
"@babel/preset-env": "^7.4.4",
"@babel/preset-react": "^7.0.0",
"autoprefixer": "^9.5.1",
"babel-loader": "^8.0.5",
"css-loader": "^2.1.1",
"cssnano": "^4.1.10",
"file-loader": "^3.0.1",
"glob": "^7.1.4",
"html-webpack-plugin": "^3.2.0",
"less": "^3.9.0",
"less-loader": "^5.0.0",
"mini-css-extract-plugin": "^0.6.0",
"optimize-css-assets-webpack-plugin": "^5.0.1",
"postcss-loader": "^3.0.0",
"px2rem-loader": "^0.1.9",
"raw-loader": "^0.5.1",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"style-loader": "^0.23.1",
"url-loader": "^1.1.2",
"webpack": "^4.31.0",
"webpack-cli": "^3.3.2",
"webpack-dev-server": "^3.3.1"
},
"dependencies": {
"lib-flexible": "^0.3.2"
}
}