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

相关文章
相关标签/搜索