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:
- How can I setup codesplitting for dynamic imports in the webpack side of things:
- Can I use React.Lazy with typescript?
I think I need to make sure ts is not removing the comments.
Answer
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.
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?