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'
Whenever you import a file in your code, Webpack will look for it in the project directory and copy it to the build folder with a new name, then Webpack replaces the import code in your bundled JavaScript file with the path to the newly copied file.
Webpack supports the following module types natively: ECMAScript modules. CommonJS modules.
The import() call, commonly called dynamic import, is a function-like expression that allows loading an ECMAScript module asynchronously and dynamically into a potentially non-module environment.
Code splitting is one of the most compelling features of webpack. This feature allows you to split your code into various bundles which can then be loaded on demand or in parallel.
Whenever you import a file in your code, Webpack will look for it in the project directory and copy it to the build folder with a new name, then Webpack replaces the import code in your bundled JavaScript file with the path to the newly copied file. What is a dynamic import?
The following methods are supported by webpack: Statically import the export s of another module. The keyword here is statically. A normal import statement cannot be used dynamically within other logic or contain variables. See the spec for more information and import () below for dynamic usage. Export anything as a default or named export.
@yvele you can, just use the magic comments: webpack.js.org/api/module-methods/#magic-comments Sure but I don't see the added value of using individual magic comments for all dynamic imports when a generic developer friendly name is OK for me.
But for this article, I’m going to use the proposed ES2015 dynamic imports supported by Webpack, since the v2, through a babel plugin and the extra specific Webpack features for it. Update: If you’re using Babel 7.5+ it already includes the dynamic import plugin for you ;)
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 })
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With