webpack和typescript中的异步代码拆分

时间:2017-05-16 10:24:44

标签: typescript asynchronous webpack

在webpack 2.2中,可以使用import().then()使用异步代码拆分(https://webpack.js.org/guides/code-splitting-async/).I无法使用打字稿。我有编译错误。 我该如何解决?

1 个答案:

答案 0 :(得分:5)

TC39 https://github.com/tc39/proposal-dynamic-import)正在将

异步代码拆分(或延迟加载)定义为标准。

TypeScript 2.4现在支持异步代码拆分。它是一种名为动态导入表达式的功能。

import (/* webpackChunkName: "momentjs" */ "moment")
    .then((moment) => {
         // lazyModule has all of the proper types, autocomplete works,
         // type checking works, code references work \o/
         const time = moment().format();
         console.log(time);
     })
     .catch((err) => {
         console.log("Failed to load moment", err);
     });

考虑到你必须使用"模块":" esnext"在tsconfig.json中。 请查看此帖子以获取更多信息:https://blog.josequinto.com/2017/06/29/dynamic-import-expressions-and-webpack-code-splitting-integration-with-typescript-2-4/

如果您使用TypeScript< 2.4,有一个已知的工作:

interface System {
  import<T> (module: string): Promise<T>
}

declare var System: System

import * as lazyModule from './lazy-loaded-file'

System.import<typeof lazyModule>('./lazy-loaded-file')
.then(lazyModule => {
  // lazyModule has all of the proper types, autocomplete works,
  // type checking works, code references work \o/
})
// the './lazy-loaded-file' static import is only used for its types so typescript deletes it
// result: type-checked code splitting with lazy loading 

来自来源https://gist.github.com/Kovensky/e2ceb3b9715c4e2ddba3ae36e9abfb05

我做了一个示例(webpack 2,React,TypeScript),使用该代码延迟加载库momentjs,你可以在这里找到:

https://github.com/jquintozamora/react-typescript-webpack2-cssModules-postCSS/blob/master/app/src/components/AsyncLoading/AsyncLoading.tsx#L47