本文總結了使用 typescript 動態載入 vue 元件的方法。原始碼在最下面。
Webpack 配置
動態載入需使用 webpack 的 codesplit
功能。需配置chunkFilename
和 publicPath
。
module.exports = {
...
output: {
//生成的檔案路徑。
path: path.resolve(__dirname, './dist'),
// 打包後資原始檔的字首
publicPath: '/dist/',
// 動態載入模組的檔名
chunkFilename: 'chunk-[id].js?[chunkhash]',
//生成的檔名
filename: 'build.js'
},
...
}
TypeScript 動態載入檔案方法
webpack + typescript 有兩種動態載入模組的方法。分別為 require
方式和es6
方式。
普通方式
webpack 可以使用 require
實現動態載入。
Vue.component('global-lazy', (resolve) => require(['./components/GlobalLazy.vue'], resolve))
注:此處的require
為 webpack 方法,沒有宣告。所以需手動宣告:
declare var require : (filename,resolve)=>any;
ES6 方式
typescript 2.4 新增了 es6 的 import 表示式,可以使用 import(filename) 動態載入。
webpack 2+ 也支援 import
表示式。
使用此方式需在tsconfig.json
中將module
設定為esnext
Vue.component('global-lazy-es6',()=> import("./components/GlobalLazy.vue"))
但是在 vue2.4.2 及之前版本在編譯時會報錯。是因為 vue 的宣告檔案(options.d.ts)沒有定義 es6 方式。
Vue.component('global-lazy-es6',()=> import("./components/GlobalLazy.vue") as any)
注:github 上 vue 的宣告檔案已新增此種方式的宣告。vue 下個釋出版本應可以直接使用此種方式,而無須新增 as any
來避免編譯時報錯。
Vue 常用非同步元件
上面介紹了 typescript+webpack 的兩種動態載入檔案方法。以下各種示例都使用 es6
方式。
區域性元件
註冊元件:
...
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 },
]
}),