代碼拆分方案
1. Code Splitting - CSS
使用插件:npm i --save-dev extract-text-webpack-plugin
+var ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
module: {
rules: [{
test: /\.css$/,
- use: 'css-loader'
+ use: ExtractTextPlugin.extract({
+ use: 'css-loader'
+ })
}]
},
+ plugins: [
+ new ExtractTextPlugin('styles.css'),
+ ]
}
2. Code Splitting - Libraries
使用:CommonsChunkPlugin
var webpack = require('webpack');
var path = require('path');
module.exports = function() {
return {
entry: {
main: './index.js',
vendor: 'moment'
// 將第三方lib,單獨打包到一個 bundle 中,充分利用瀏覽器基于內容的 hash 緩存策略
},
output: {
filename: '[name].[chunkhash].js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: function (module) {
// this assumes your vendor imports exist in the node_modules directory
return module.context && module.context.indexOf('node_modules') !== -1;
}
}),
//CommonChunksPlugin will now extract all the common modules from vendor and main bundles
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest'
//每次webpack工程時運行時代碼發生改變,單獨抽取運行時代碼到清單文件中,
// 所產生的開銷通過瀏覽器緩存 Vendor 文件可以抵消回來
})
]
};
}
3. Code Splitting - Using import()
使用:
- npm install --save-dev babel-core babel-loader babel-plugin-syntax-dynamic-import babel-preset-es2015
- npm install --save moment
function determineDate() {
import('moment')
.then(moment => moment().format('LLLL'))
.then(str => console.log(str))
.catch(err => console.log('Failed to load moment', err));
}
determineDate();
- Usage with Babel and async / await
To use ES2017 async
/await
with import()
使用:npm install --save-dev babel-plugin-transform-async-to-generator babel-plugin-transform-regenerator babel-plugin-transform-runtime
async function determineDate() {
const moment = await import('moment');
return moment().format('LLLL');
}
determineDate().then(str => console.log(str));
webpack.config.js
module.exports = {
entry: './index-es2017.js',
output: {
filename: 'dist.js',
},
module: {
rules: [{
test: /\.js$/,
exclude: /(node_modules)/,
use: [{
loader: 'babel-loader',
options: {
presets: [['es2015', {modules: false}]],
plugins: [
'syntax-dynamic-import',
'transform-async-to-generator',
'transform-regenerator',
'transform-runtime'
]
}
}]
}]
}
};
4. Code Splitting - Using require.ensure
webpack提出代碼拆分的方案,可以將應用代碼拆分為多個(chunk),每個塊包含一個或多個模塊,塊可以按需異步加載
語法:
require.ensure(dependencies: String[], callback: function(require), chunkName: String)
require('./a');
require.ensure(["module-a"],function(require){
var a = require("./b");
}, 'custom-chunk-name');
var a = require("./c");
// module-a.js 和 b.js 綁定在一起,并從主包中拆分。但是只執行 b.js 的內容。 module-a.js的內容只能提供,不能執行。
// 要執行module-a.js,必須使用同步的方式來要求它,例如require('./module-a.js')來執行JavaScript。
通過require.ensure聲明依賴module-a,module-a的實現及其依賴會被合并為一個單獨的塊,對應一個結果文件
當執行到require.ensure才去加載module-a所在的結果文件,并在module-a加載就緒后在執行傳入的回調函數。(其中加載行為和回調函數執行時機控制由webpack實現。這對業務代碼的侵入性極?。?br>
在真實使用中,需要被拆分出來的可能是某個體積極大的第三方庫(延后加載并使用),也可能是一個點擊觸發浮層的內部邏輯(除非觸發條件得到滿足,否則不需要加載執行),異步加載可以讓我們以極小的代價,來極大地提升大規模單頁面應用的初始加載速度
**
import 取代 require.ensure
Good news: Failure to load a chunk can be handled now because they are Promise based.
import 由于它是基于 Promise的,現在還不能加載 chunk**
**Caveat: require.ensure allows for easy chunk naming with the optional third argument, but import API doesn't offer that capability yet.
注意事項:require.ensure允許使用可選的第三個參數進行簡單的塊命名,但是 import API 還沒有提供該功能。
**
模塊熱替換
webpack-dev-server --hot