Dynamic import named export using Webpack
Asked Answered
S

1

20

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'

Sightseeing answered 23/1, 2019 at 0:44 Comment(0)
L
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 })
})
Libyan answered 23/1, 2019 at 0:48 Comment(3)
what is this dynamic function wrapped around import in first example?Methanol
Its useful for code-splitting / lazy loading. Syntax has changed. You can read about it here: reactjs.org/docs/code-splitting.htmlLibyan
This will import the whole library. There is a not so well documented magic comment called webpackExports that only imports specified modules: webpack.js.org/api/module-methods/#magic-comments. See also blog.sasivarnan.com/dynamic-import-named-exports-in-javascript import(/* webpackExports: ["default", "sum"] */ "./lib/math.js").then((module) => { const { default as Math, sum } = module; });Euchre

© 2022 - 2024 — McMap. All rights reserved.