Skip to content

Commit 8e1e8b1

Browse files
tiendo1011montogeek
authored andcommitted
docs(guides) Update code-splitting.md (#2153)
* Update code-splitting.md Since webpack 4, when using `dynamic import` to resolve commonJS module, it no longer resolve directly to the value of `module.exports`, but create an artificial namespace object to wrap it instead. * Update code-splitting.md
1 parent e24bfb6 commit 8e1e8b1

File tree

1 file changed

+6
-3
lines changed

1 file changed

+6
-3
lines changed

src/content/guides/code-splitting.md

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ contributors:
2424
- kcolton
2525
- efreitasn
2626
- EugeneHlushko
27+
- Tiendo1011
2728
- byzyk
2829
related:
2930
- title: <link rel=”prefetch/preload”> in webpack
@@ -232,7 +233,7 @@ __src/index.js__
232233
-
233234
- // Lodash, now imported by this script
234235
- element.innerHTML = _.join(['Hello', 'webpack'], ' ');
235-
+ return import(/* webpackChunkName: "lodash" */ 'lodash').then(_ => {
236+
+ return import(/* webpackChunkName: "lodash" */ 'lodash').then(({ default: _ }) => {
236237
+ var element = document.createElement('div');
237238
+ var _ = _.default;
238239
+
@@ -249,6 +250,8 @@ __src/index.js__
249250
+ })
250251
```
251252

253+
The reason we need `default` is since webpack 4, when importing a CommonJS module, the import will no longer resolve to the value of `module.exports`, it will instead create an artificial namespace object for the CommonJS module, for more information on the reason behind this, read [webpack 4: import() and CommonJs](https://medium.com/webpack/webpack-4-import-and-commonjs-d619d626b655)
254+
252255
Note the use of `webpackChunkName` in the comment. This will cause our separate bundle to be named `lodash.bundle.js` instead of just `[id].bundle.js`. For more information on `webpackChunkName` and the other available options, see the [`import()` documentation](/api/module-methods#import-). Let's run webpack to see `lodash` separated out to a separate bundle:
253256

254257
``` bash
@@ -272,7 +275,7 @@ __src/index.js__
272275
``` diff
273276
- function getComponent() {
274277
+ async function getComponent() {
275-
- return import(/* webpackChunkName: "lodash" */ 'lodash').then(_ => {
278+
- return import(/* webpackChunkName: "lodash" */ 'lodash').then({ default: _ } => {
276279
- var element = document.createElement('div');
277280
-
278281
- element.innerHTML = _.join(['Hello', 'webpack'], ' ');
@@ -281,7 +284,7 @@ __src/index.js__
281284
-
282285
- }).catch(error => 'An error occurred while loading the component');
283286
+ var element = document.createElement('div');
284-
+ const _ = await import(/* webpackChunkName: "lodash" */ 'lodash');
287+
+ const { default: _ } = await import(/* webpackChunkName: "lodash" */ 'lodash');
285288
+
286289
+ element.innerHTML = _.join(['Hello', 'webpack'], ' ');
287290
+

0 commit comments

Comments
 (0)