【问题标题】:Async code splitting in webpack and typescriptwebpack 和 typescript 中的异步代码拆分
【发布时间】:2017-10-15 09:08:53
【问题描述】:

在 webpack 2.2 中,可以使用 import().then() 使用异步代码拆分(https://webpack.js.org/guides/code-splitting-async/).I 无法使其与 typescript 一起使用。我遇到了编译错误。 我该如何解决?

【问题讨论】:

  • 你能发布你的代码以及你得到什么编译错误吗?

标签: typescript asynchronous webpack


【解决方案1】:

异步代码拆分(或延迟加载)已被 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);
     });

考虑到你必须在 tsconfig.json 中使用 "module": "esnext"。 请查看此帖子以获取更多信息:https://blog.josequinto.com/2017/06/29/dynamic-import-expressions-and-webpack-code-splitting-integration-with-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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-11
    • 2018-06-21
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 2016-08-27
    • 2018-10-08
    • 2016-12-28
    相关资源
    最近更新 更多