Search code examples
javascriptwebpackcode-splitting

Dynamic import named export using Webpack


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'


Solution

  • 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 })
    })