1. 程式人生 > >【webpack學習筆記】a07-程式碼分離

【webpack學習筆記】a07-程式碼分離

官方文件說進行程式碼分離有三種方法:

  1. 入口起點:使用entry配置手動分離。
  2. 防止重複:使用CommonsChunkPlugin外掛去重合分離chunk
    注:在webpack4中,CommonsChunkPlugin已經被廢棄,改用optimization.splitChunks
  3. 動態分離

但是在個人理解:2是對1的缺陷補充,所以其實就只有兩種分離方法:

  • 入口起點手動靜態分離
  • 動態分離

靜態分離:

index.js

import _ from 'lodash';

function component (){
    var element = document.createElement('div');
    element.innerHTML = _.join(['hello','2019~'], ' ');

    return element;
}

document.body.appendChild(component());

another-module.js

import _ from 'lodash';

console.log(
    _.join(['Another','module','loadsh!'],' ')
)

webpack.config.js

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');

module.exports = {
    entry: {
        index: './src/index.js',
        another: './src/another-module.js'
    },
    devtool: 'inline-source-map',
    plugins:[
        new CleanWebpackPlugin(['dist']),
        new HtmlWebpackPlugin({
            title: 'Code Splitting',
            template: './src/index.html'
        })
    ],
    optimization:{
        splitChunks: {
            cacheGroups: {
                commons: {
                    name: "commons",
                    chunks: "initial",
                    minChunks: 2
                }
            }
        }
    },
    output: {
        filename: '[name].build.js',
        path: path.resolve(__dirname, 'dist')
    }
}

動態分離:

index.js

function getComponent(){
    return import(/* webpackChunkName:'lodash' */'lodash').then(_ => {
        var element = document.createElement('div');

        element.innerHTML = _.join(['Hello','2019~'], ' ');

        return element;
    }).catch(error => 'An error occurred while loading the component');
}

getComponent().then(component => {
    document.body.appendChild(component);
})

webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');

module.exports = {
    entry:{
        index: './src/index.js'
    },
    plugins:[
        new CleanWebpackPlugin(['dist']),
        new HtmlWebpackPlugin({
            title: 'Code splitting',
            template: './src/index.html'
        })
    ],
    output:{
        filename: '[name].bundle.js',
        chunkFilename: '[name].bundle.js',
        path:path.resolve(__dirname,'dist')
    }
}