2

This question may look similar to The difference between "require(x)" and "import x" but it's actually different.

I noticed the usage of await import recently, in Next.js projects such as: https://github.com/zeit/next.js/blob/canary/examples/with-apollo/lib/apollo.js#L134

if (ssr && AppTree) {
    // Import `@apollo/react-ssr` dynamically.
    // We don't want to have this in our client bundle.
    const { getDataFromTree } = await import('@apollo/react-ssr')
}

At first glance, I believe the use of await import('@apollo/react-ssr') allows to use import within the source code (conditionally), instead of importing the @apollo/react-ssr module at the top-level. The goal is to reduce the generated bundle for the browser (the browser will not contain @apollo/react-ssr package).

Until now, I've always used const reactSSR = require('@apollo/react-ssr') to conditionally import packages. I wonder what difference there are between both ways.

Maybe using await import('@apollo/react-ssr') is better because it allows tree-shacking? Are there any "cons" of using it compared to require?

Vadorequest
  • 14,569
  • 21
  • 102
  • 201

0 Answers0