vue2 + typescript + webpack2 动态加载组件方法

本文总结了使用 typescript 动态加载 vue 组件的方法。源码在最下面。

Webpack 配置

动态加载需使用 webpack 的 codesplit 功能。需配置chunkFilenamepublicPath

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 },
    ]
  }),

源码

github:vue-demo

参考文章

  1. TypeScript 2.4
  2. Vue:AsyncComponents
  3. Lazy Loading in Vue using Webpack’s Code Splitting
    原文作者:meteor199
    原文地址: https://segmentfault.com/a/1190000011935026
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞