1. 程式人生 > 實用技巧 >webpack按需載入

webpack按需載入

什麼是按需載入:

當頁面中一個檔案過大並且還不一定用到的時候,我們希望在使用到的時候才開始載入這個檔案俗稱按需載入。這樣可以減少頁面的響應時間,提高訪問速度。

按需載入的實現方式:

使用webpack打包的出來的檔案要實現以上的要求有兩種方式,一個是webpack特有的require.ensure方法,還有一個是import()方法。

方法一:

require.ensure()方法:require.ensure(dep: array, cb: function, name?: string)

第一個引數是該模組的依賴,第二個引數是模組載入完成後執行的回撥,第三個引數是對應webpack.config.js中output.chunkFilename: ‘[name].js’ 中的name。

樣例:

index.html檔案:
<button id='btn'>點選我</button>


index.js檔案:
document.querySelector('#btn').onclick = function () {
  require.ensure([], function () {
    let a = require('./asynca.js')
    console.log('asynca模組載入完畢:'a)
  }, 'asynca')
}


asynca.js檔案:
console.log('我是async模組')
export const a = '模組async'


webpack.config.js檔案:
let path = require('path')
let HtmlWebpackPlugin = require('html-webpack-plugin')

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

asynca檔案被動態載入進來,並且require.ensure的回撥函式被執行了。

方法二:

import():該方法返回一個promise,檔案載入完成之後會將模組匯出給promise的回撥。

document.querySelector('#btn').onclick = function () {
  console.log('我是通過import來實現按需載入的')
  let a = import('./asynca.js')
  a.then(function (res) {
    console.log('載入完成的async模組', res)
  })
}

  

參考:https://blog.csdn.net/letterTiger/article/details/89299606