19

Using webpack, if I want to code-split an entire module, I can change

import Module from 'module'

at the top of my file to

import('module').then(Module => {...

when I need to use the module (docs). Is it possible to do this but with just a single named export? That is, how could I code-split the following:

import {namedExport} from 'module'

Daniel Elkington
  • 2,560
  • 6
  • 22
  • 35

1 Answers1

19
const DynamicFoo = dynamic(import('../components/Foo').then(module => {
  const {Foo} = module
  return Foo
}));

OR

import(/* webpackChunkName: "chunkName" */ '../component/Foo').then(module => {
  const {Foo} = module.default
  this.setState({ foo: Foo })
})
varoons
  • 3,807
  • 1
  • 16
  • 20
  • 2
    what is this `dynamic` function wrapped around import in first example? – ips May 13 '21 at 05:48
  • Its useful for code-splitting / lazy loading. Syntax has changed. You can read about it here: https://reactjs.org/docs/code-splitting.html – varoons May 13 '21 at 20:09
  • 5
    This will import the whole library. There is a not so well documented magic comment called `webpackExports` that only imports specified modules: https://webpack.js.org/api/module-methods/#magic-comments. See also https://blog.sasivarnan.com/dynamic-import-named-exports-in-javascript `import(/* webpackExports: ["default", "sum"] */ "./lib/math.js").then((module) => { const { default as Math, sum } = module; });` – Giorgio Tempesta Mar 23 '22 at 06:16