React: Named imports in lazy feature

Created on 4 Dec 2018  路  5Comments  路  Source: facebook/react

Hi guys,

How could I import named imports using lazy syntax?

Before we could use

import { MainComponent, Component1, Component2 } from './components';

How to achieve something like this (although this does not work)?:

const { MainComponent, Component1, Component2 } = React.lazy(() => import('./components'));

Thank you and have a good day :-)

Most helpful comment

This is how I do it.

const Contacts = React.lazy(() =>
  import('./Contacts.js').then(module => ({ default: module.Contacts }))
);

All 5 comments

Looks like it's not yet available

If the module you want to import uses named exports, you can create an intermediate module that reexports it as the default.

I think that's the only solution for now

This is how I do it.

const Contacts = React.lazy(() =>
  import('./Contacts.js').then(module => ({ default: module.Contacts }))
);

@TrySound Thank you for that. Still we need to import every component separately though.

@barth12 yeah, that's the one big caveat with how React.lazy works with named exports right now. It expects that you're importing exactly one component. You won't currently be able to use destructuring like you want, they'll have to be separate React.lazy calls as @TrySound illustrated.

Closing since this is a documented shortcoming and expected behavior for now.

I try with this ->

const myComponent = React.lazy(() => import('../MyComponent'), 'default');

It works fine!

Was this page helpful?
0 / 5 - 0 ratings