vue2 + typescript + webpack2 動態加載組件方法

本文總結了使用 typescript 動態加載 vue 組件的方法。源碼在最下面。html

Webpack 配置

動態加載需使用 webpack 的 codesplit 功能。需配置chunkFilenamepublicPathvue

module.exports = {
  ...
  output: {
    //生成的文件路徑。
    path: path.resolve(__dirname, './dist'),
    // 打包後資源文件的前綴
    publicPath: '/dist/',
    // 動態加載模塊的文件名
    chunkFilename: 'chunk-[id].js?[chunkhash]',
    //生成的文件名
    filename: 'build.js'
  },
  ...
}

TypeScript 動態加載文件方法

webpack + typescript 有兩種動態加載模塊的方法。分別爲 require 方式和es6方式。webpack

普通方式

webpack 能夠使用 require 實現動態加載。git

Vue.component('global-lazy', (resolve) => require(['./components/GlobalLazy.vue'], resolve))

注:此處的require 爲 webpack 方法,沒有聲明。因此需手動聲明:es6

declare var require : (filename,resolve)=>any;

ES6 方式

typescript 2.4 添加了 es6 的 import 表達式,能夠使用 import(filename) 動態加載。
webpack 2+ 也支持 import 表達式。
使用此方式需在tsconfig.json 中將module 設置爲esnextgithub

Vue.component('global-lazy-es6',()=> import("./components/GlobalLazy.vue"))

可是在 vue2.4.2 及以前版本在編譯時會報錯。是由於 vue 的聲明文件(options.d.ts)沒有定義 es6 方式。web

Vue.component('global-lazy-es6',()=> import("./components/GlobalLazy.vue") as any)

注:github 上 vue 的聲明文件已添加此種方式的聲明。vue 下個發佈版本應能夠直接使用此種方式,而無須添加 as any 來避免編譯時報錯。typescript

Vue 經常使用異步組件

上面介紹了 typescript+webpack 的兩種動態加載文件方法。如下各類示例都使用 es6 方式。json

局部組件

註冊組件:異步

...
  components: {
    ...
    'local-lazy': () => import("./components/LocalLazy.vue") as any
  },
...

使用組件

<local-lazy  />

全局組件

Vue.component('global-lazy-es6',()=> import("./components/GlobalLazy.vue") as any)

路由

router: new VueRouter({
    routes: [
      { path: '/RouterLazy', component:(()=> import("./components/RouterLazy.vue")) as any },
    ]
  }),

源碼

github:vue-demo

參考文章

  1. TypeScript 2.4
  2. Vue:AsyncComponents
  3. Lazy Loading in Vue using Webpack's Code Splitting
相關文章
相關標籤/搜索