piernik
piernik

Reputation: 3657

Async code splitting in webpack and typescript

In webpack 2.2 one can use async code splitting using import().then() (https://webpack.js.org/guides/code-splitting-async/).I cannot get it to work with typescript. I've got compilation errors. How do I fix it?

Upvotes: 1

Views: 1284

Answers (1)

José Quinto Zamora
José Quinto Zamora

Reputation: 2118

Async Code Splitting (or Lazy Loading) is being defined as standard by TC39 (https://github.com/tc39/proposal-dynamic-import).

Async Code Splitting is now supported by TypeScript 2.4. It's a feature called Dynamic Import Expressions.

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);
     });

Take into account you must use "module": "esnext" in tsconfig.json. Take a look to this post for further information: https://blog.josequinto.com/2017/06/29/dynamic-import-expressions-and-webpack-code-splitting-integration-with-typescript-2-4/

If you are using TypeScript < 2.4, there is a known work around:

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 

From the source: https://gist.github.com/Kovensky/e2ceb3b9715c4e2ddba3ae36e9abfb05

I did an example (webpack 2, React, TypeScript) using that code lazy loading the library momentjs, you can find here:

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

Upvotes: 6

Related Questions