TypeScript React App Code Splitting

TypeScript React App Code Splitting

路由

import * as React from 'react';
import { Route } from 'react-router-dom';
import { Loading } from "./Loading";
import { default as Loadable } from "react-loadable";

export const Routes = () => {
    return <div>
        <Route path="/test"
               component={ Loadable({
                   loading: Loading,
                   loader: () => import('./TestApp').then(x => x.TestApp)
               }) }/>
    </div>;
};
  1. import 模块与 JavaScript 不同。
  2. export 组件如果不是 export default 在 dynamic import 之后要 then。

Webpack Config

{
    test: /\.(ts|tsx)$/,
    include: paths.appSrc,
    use: [
        {
            loader: 'babel-loader',
            options: {
                presets: [
                    ["env"],
                ],
                babelrc: false,
                plugins: ['syntax-dynamic-import']
            },
        },
        {
            loader: require.resolve('ts-loader'),
            options: {
                transpileOnly: true,
                configFile: 'tsconfig.react.json'
            },
        },
    ],
}
  1. 使用 syntax-dynamic-import, 如果 babel@7 是 @babel/plugin-syntax-dynamic-import

Tsconfig

{
  "compilerOptions": {
    "module": "esnext",
    "declaration": false,
    "removeComments": true,
    "noLib": false,
    "allowSyntheticDefaultImports": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es6",
    "outDir": "./build",
    "sourceMap": true,
    "allowJs": true,
    "lib": [
      "es6",
      "dom",
      "esnext.asynciterable"
    ],
    "jsx": "react",
    "moduleResolution": "node",
    "rootDir": "src",
    "baseUrl": ".",
    "forceConsistentCasingInFileNames": true,
    "noImplicitAny": false,
    "noUnusedLocals": true
  }
}
  1. 如果 module 为 commonjs 而不是 esnest,dynamic import 会无效
miaowing
A Javascript & Typescript developer
Posted on 2019-11-17

Share this post

Scan to open in WeChat

Stay tuned

  • Add me on WeChat

  • Subscribe to my newsletter