I've created a web application with React and Typescript, using create-react-app. It uses a rather heavy third party library. I want to exclude that from the main bundle by using dynamic import expressions.
So, instead of doing import { Component } from 'library'
, I've created a little wrapper that looks like this:
const loadLibrary = async () => {
const x = await import('library').then((r) => r);
return x;
};
const {
Component,
} = loadLibrary() as any;
// tslint:disable-next-line:no-console
console.log(`typeof Component is ${typeof Component}`);
export {
Component,
};
And then, in my app, I'd use import { Component } from '../library-wrapper.ts'
.
Because the wrapper uses dynamic import expressions, Webpack creates a separate chunk which is only downloaded by the browser then it is actually needed. \o/
.
But the bad news is: my wrapper doesn't actually await the dynamic import expression. It invokes the loadLibrary()
function but immediately continues execution, logging
typeof Component is undefined
So when I attempt to use the Component
, React crashes:
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.
Any suggestions what is going on?
Promise
to be resolved. Have I been wrong in this case? – Rockett