前言
webpack4都發布一年多了,爲啥還要寫webpack3的博客呢?因爲只有更瞭解 webpack3
有哪些新功能,才能知道 webpack4
在 webpack3
的基礎上又哪些優化。
目錄結構
.
├── dist
│ └── bundle.js
├── package.json
├── src
│ ├── index.js
│ └── string.js
├── webpack.config.js
└── yarn.lock
webapck3新特性
webpck3
主要有2個新特性
Scope Hoisting
(作用域提升)Magic Comments
(魔法註釋)
Scope Hoisting
在 webpack3
之前打包都會將每個模塊打包到自己的閉包函數中,整體增加了打包後 js
文件的大小,且增加了瀏覽器運行 js
的時間。然 webpack3
參考了 Closure Compiler
和 RollupJS
這樣的工具,將所有模塊打包後放置到一個閉包函數中,從而減少了打包後文件大小,減少了瀏覽器運行耗時。
安裝 webpack3
yarn add webpack@3.0.0 -D
在 package.json
中添加腳本
"scripts": {
"build": "webpack -p --config webpack.config.js",
"build:dev": "webpack --config webpack.config.js"
}
webpack.config.js
配置文件
const path = require('path')
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
}
index.js
import sayHello from './string'
sayHello()
var t = Date.now()
var a = 1
var b = 2
var c = 3
var d = a + b + c
console.log(t, '**************', d)
string.js
export default function () {
return 'hello world'
}
執行打包命令 yarn build:dev
可以觀察到上圖有2個閉包函數,分別對應2個模塊 index.js
和 string.js
執行打包命令 yarn build
雖然並沒有打印 index.js
中 sayHello()
函數的值,但打包後文件 bundle.js
中依然有模塊 string.js
的代碼。
使用作用域提示,在 webpack.config.js
添加如下配置
const path = require('path')
const webpack = require('webpack')
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new webpack.optimize.ModuleConcatenationPlugin()
]
}
執行打包命令,yarn build:dev
可以觀察到,此時只有1個閉包函數了,這就是 webpack3
提供的新插件達到作用域提升的效果。
執行打包命令,yarn build
可以觀察到,webpack3
巧妙的計算了需要打印的變量的值,去除了變量 a
、b
、c
、d
,進一步精簡了代碼。
Magic Comments
在 webpack3
中可以在動態導入 import()
語法中以註釋的方式命名 chunk
代碼塊的的名稱。
語法如下:
import(/* webpackChunkName: "my-chunk-name" */ 'module');
添加 chunk
配置
webpack.config.js
const path = require('path')
const webpack = require('webpack')
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
chunkFilename: '[name].chunk.js'
},
plugins: [
new webpack.optimize.ModuleConcatenationPlugin()
]
}
index.js
import(/* webpackChunkName: "string" */'./string').then(function(res){
console.log(res)
})
var t = Date.now()
var a = 1
var b = 2
var c = 3
var d = a + b + c
console.log(t, '**************', d)
執行打包命令,yarn build
此時目錄結構爲:
.
├── dist
│ ├── bundle.js
│ └── string.chunk.js
├── package.json
├── src
│ ├── index.js
│ └── string.js
├── webpack.config.js
└── yarn.lock
總結
- 在使用
webpack3
時,添加上作用域提升的ModuleConcatenationPlugin
插件能進一步精簡打包後的代碼 - 魔法註釋可以分割代碼塊,並實現懶加載。
參考
https://zhuanlan.zhihu.com/p/27474985
https://jdc.jd.com/archives/212653