To Add .default Or Not?: Dynamic Imports In React Router 3 For Webpack Code-splitting
Solution 1:
After days of research, I finally found the answer to my question, hoping I can somehow help those with the same question in the future.
Webpack official website (Code-Splitting: Dynamic Import) has a description as follows:
The reason we need default is that 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.
Out of curiosity, I did some experiment logging out things I dynamic imports:
// exportObject.jsexportdefault {a: 1, b: 2};
exportconst c = 3;
// exportString.jsexportdefault"TEST_STRING";
// exportComponent.jsimportReact, {Component} from"react";
exportdefaultclassexportComponentextendsComponent {
constructor(props) {
super(props);
this.a = 1;
this.b = 2;
}
}
// exportFunction.jsexportdefault () => ({a: 1, b: 2});
// index.jscomponentDidMount() {
import('./exportObject').then(module => {
console.group('Object');
console.warn('module', module);
console.warn('module.a:', module.a);
console.warn('module.b:', module.b);
console.warn('module.default', module.default);
console.warn('module.c', module.c);
console.groupEnd();
});
import('./exportString').then(module => {
console.group('String');
console.warn('module', module);
console.warn('module.default', module.default);
console.groupEnd();
});
import('./exportComponent').then(module => {
console.group('Component');
console.warn('module', module);
console.warn('module.default', module.default);
console.groupEnd();
});
import('./exportFunction').then(module => {
console.group('Function');
try {
console.warn('module()', module());
} catch (e) {
console.warn('module()', e);
}
try {
console.warn('module.default()', module.default());
} catch (e) {
console.warn('module.default()', e);
}
console.groupEnd();
});
}
This is the result from Webpack 3 Project:
While from Webpack 4 Project:
As you can see, non-objects have different results. This finding matches the description of this article (which is provided by webpack official)
It’s not that problematic when exporting an object. But you’ll get into trouble when using module.exports with non-objects.
I use export default
in my code rather than module.exports
, then why I still got the result?
Actually, Babel@6 will do the transform as below: (reference)
Babel@6 transforms the following file
exportdefault'foo'
into
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = 'foo';
Now, things are crystal clear.
The packages I used was:
node:11.15.0
babel-core: "^6.23.1",
babel-loader: "7.1.4",
webpack:"4.44.2",
webpack-cli: "^4.2.0",
Post a Comment for "To Add .default Or Not?: Dynamic Imports In React Router 3 For Webpack Code-splitting"