最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use React.lazy for a component of a module? - Stack Overflow

programmeradmin3浏览0评论

I am using the npm package called '@toast-ui/react-editor'. It includes a 'Viewer' react component. I could just use:

const Viewer = require("@toast-ui/react-editor").Viewer

But it increases the bundle size a lot. So I wanted to load it lazily whenever it is needed by using React.lazy. I am going to use it inside component:

<Viewer {...props} />

But I don't have any clue how to do it.

I tried this way, but didn't work.

const Lazy = React.lazy(() => import(require("@toast-ui/react-editor"))).Viewer;

I really want to know how to do it.

I am using the npm package called '@toast-ui/react-editor'. It includes a 'Viewer' react component. I could just use:

const Viewer = require("@toast-ui/react-editor").Viewer

But it increases the bundle size a lot. So I wanted to load it lazily whenever it is needed by using React.lazy. I am going to use it inside component:

<Viewer {...props} />

But I don't have any clue how to do it.

I tried this way, but didn't work.

const Lazy = React.lazy(() => import(require("@toast-ui/react-editor"))).Viewer;

I really want to know how to do it.

Share Improve this question edited Aug 21, 2019 at 14:39 adamaero 2183 silver badges17 bronze badges asked Aug 21, 2019 at 13:31 Dream HighDream High 1732 silver badges11 bronze badges 4
  • you can skip the require inside import – Agney Commented Aug 21, 2019 at 13:33
  • Can you remove require inside import – GRS Commented Aug 21, 2019 at 13:34
  • is it working when you remove the require ? – GRS Commented Aug 21, 2019 at 14:08
  • yes, I did but it didn't work. – Dream High Commented Aug 22, 2019 at 14:59
Add a comment  | 

1 Answer 1

Reset to default 21

As Viewer is not a default component, it's not as simple as removing require, (which is not even needed, though).

You need to import it dynamically and then return the module as a default one (as that's what lazy expects and works with only).

const Viewer = lazy(() =>
  import("@toast-ui/react-editor").then(module => {
    return { default: module.Viewer };
  })
);
发布评论

评论列表(0)

  1. 暂无评论