webpack3.0構建學習總結(三)

提取公共代碼

減小代碼冗餘, 加快加載速度
plugins: CommonsChunkPlugin(webpack自帶)javascript

配置:java

{
    plugins: [
        new webpack.optimize.CommonsChunkPlugin(option)
    ]
}
複製代碼
1. options.name 和 options.names
2. options.filename(公共文件名)
3. options.minChunks(最小出現幾回開始打包)
4. options.chunks(提取代碼的範圍)
複製代碼
//提取公共的js
var webpack = require('webpack');
var path = require('path');

module.exports = {
    entry: {
        'pageA': './src/pageA',
        'pageB': './src/pageB',
    },
    output: {
        path: path.resolve(__dirname, './dist'),
        filename: '[name].bundle.js',
        chunkFilename: '[name].chunk.js'
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
            name: 'common',
            minChunks: 2
        })
    ]
}
複製代碼
var webpack = require('webpack');
var path = require('path');

module.exports = {
    entry: {
        'pageA': './src/pageA',
        'pageB': './src/pageB',
        //把第三方代碼和公共業務代碼區分開
        'vendor': ['xxxx']
    },
    output: {
        path: path.resolve(__dirname, './dist'),
        filename: '[name].bundle.js',
        chunkFilename: '[name].chunk.js'
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendor',
            minChunks: Infinity //不須要再重複出現
        })
    ]
}
複製代碼

若是想保持第三方代碼的純淨不與webpack代碼混淆。webpack

var webpack = require('webpack');
var path = require('path');

module.exports = {
    entry: {
        'pageA': './src/pageA',
        'pageB': './src/pageB',
        //把第三方代碼和公共代碼區分開
        'vendor': ['xxxx']
    },
    output: {
        path: path.resolve(__dirname, './dist'),
        filename: '[name].bundle.js',
        chunkFilename: '[name].chunk.js'
    },
    plugins: [
       //提取公共業務代碼
        new webpack.optimize.CommonsChunkPlugin({
            name: 'common',
            minChunks: 2,
            chunks: ['pageA', 'pageB']
        }),
        //new webpack.optimize.CommonsChunkPlugin({
        // name: 'vendor',
        // minChunks: Infinity //不須要再重複出現
        //}),
        //使第三方庫和業務代碼分開
        //new webpack.optimize.CommonsChunkPlugin({
        // name: 'manifast',
        // minChunks: Infinity //不須要再重複出現
        //})
        new webpack.optimize.CommonsChunkPlugin({
            name: ['vendor', 'manifast'],
            minChunks: Infinity //不須要再重複出現
        }),
    ]
}
複製代碼

代碼分割和懶加載

import './subPageA';
import './subPageB';
//import * as _ from 'lodash';

//代碼分割
//動態import (import(/*webpackChunkName: 'subpageA'*/,'./xxxx').then(function() {}))
require.ensure([], function(){
    var _ = require('lodash');
    _.join(['1', '2'], '3');
}, 'vendor');

export default 'pageA';
複製代碼

publicPath: 告訴webpack動態加載進來的路徑是什麼web

相關文章
相關標籤/搜索