webpack-5-代碼分割

官網地址:webpack官網

代碼拆分是webpack最引人注目的功能之一。此功能使您可以將代碼分成多個捆綁包,然後可以按需或並行加載。它可用於實現較小的捆綁包並控制資源負載優先級,如果正確使用,則會對負載時間產生重大影響。

共有三種通用的代碼拆分方法:

  1. 入口點:使用entry配置手動拆分代碼。
  2. 防止重複:使用SplitChunksPlugin重複數據刪除和拆分塊。
  3. 動態導入:通過模塊內的內聯函數調用拆分代碼。

1. entry(入口點)

webpack.config.js

const path = require('path');
module.exports = {
  mode: 'development',
  entry: {
    index: './src/index.js',
   another: './src/another-module.js',
  },
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
};

entry裏面配置的會在dist裏面生成相應的.js文件,但是存在以下缺陷

  1. 如果有重複使用的模塊,則它們將同時包含在多個地方(使用他們的地方,例:index.js和another.js都使用了lodash,那麼打包後,在dist文件夾下的index.js和another.js就都有lodash)。
  2. 它不那麼靈活,不能用於通過核心應用程序邏輯動態拆分代碼。

2. SplitChunksPlugin

使用這個就可以將重複使用的模塊拆分出來
webpack.config.js

const path = require('path');
module.exports = {
    entry: {
        index: './src/index.js',
        another: './src/another.js'
    },
    output: {
        filename: "[name].js",
        path: path.resolve(__dirname,'dist'),
    },
    optimization: {
        splitChunks: {
            chunks: "all"
        }
    }
};

添加了optimization這個之後,重新編譯後,正常的話dist裏面會多出公共的js,index.js和another.js會變小。optimization配置項詳情地址:SplitChunks插件

使用官網的 dependOn 發現報錯了,entry.[index]的值應該是一個數組或者是字符串。我想也許是因爲更新爲5.0後去掉了之前的用法吧。所以我就不用這個了,直接使用splitChunks

3. 動態導入

src/index.js

function getComponent() {

    return import('lodash').then(({default: _}) => {
        const element = document.createElement('div');

        element.innerHTML = _.join(['hello','webpack'], "-");

        return element;
    }).catch(err => 'An err');
}

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

還可以寫成

async function getComponent() {

    const element = document.createElement('div');
    const {default: _} = await import('lodash');

    element.innerHTML = _.join(['hello','webpack'], "-");

    return element;
}

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

和es6的promise是不是很像。

4. 預取,預加載

webpack的import和es6的不同,可以在函數裏面使用,當執行a.js時 import 一個模塊b,這就是預加載(Preloading modules)。當點擊按鈕時 import c模塊,這就是預取( Prefetching)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章