Search code examples
reactjstypescriptwebpackcode-splitting

code splitting with dynamic imports with typescript


I am really struggling to find any good examples for typescript and code splitting.

There are babel plugins that cover this but really thin on the ground for typescript examples.

I am using react so I would like to use React.Lazy but I cannot find anything that covers the webpack code splitting side of things

I did find this old example but it uses the now deceased CommonsChunkPlugin:

plugins: [
    new webpack.optimize.CommonsChunkPlugin({
        name: "vendor",
        minChunks: function (module) {
          // this assumes your vendor imports exist in the node_modules directory
          return module.context && module.context.includes("node_modules");
        }
      })
],

It uses react-loadable but obviously cannot use the babel plugin so the example is manually adding the magic webpack comments:

export const LoadableHello = Loadable({
    loader: () => import(/* webpackChunkName: "hello" */ "./Hello"),
    loading: () => <div>loading ...</div>
});

Can anyone help me understand:

  1. How can I setup codesplitting for dynamic imports in the webpack side of things:
  2. Can I use React.Lazy with typescript?

I think I need to make sure ts is not removing the comments.


Solution

  • The answer was to ensure these values were set in my tsconfig.json:

    "compilerOptions": {
        "jsx": "react",
        "lib": ["es5", "es2015", "es2016", "dom", "es2015.promise"],
        "module": "esnext",
        "moduleResolution": "node"
      },
    

    I then need to add the magical webpack comment to any lazy import, maybe you don't need to do this if you are using babel and typescript:

    const TreeContainer = React.lazy(() =>
      import(/*
      webpackChunkName: "tree-container",
      webpackPrefetch: true
    */ '../TreeContainer')
    );
    

    This only worked on webpack 4.28.4. 4.29.x did not work.