[英]ES6 Destructuring and Module imports
I was under the impression that this syntax:我的印象是这种语法:
import Router from 'react-router';
var {Link} = Router;
has the same final result as this:最终结果与此相同:
import {Link} from 'react-router';
Can someone explain what the difference is?有人能解释一下有什么区别吗?
(I originally thought it was a React Router Bug .) (我原本以为是React Router Bug 。)
import {Link} from 'react-router';
imports a named export from react-router
, ie something like从
react-router
导入命名导出,即类似
export const Link = 42;
import Router from 'react-router';
const {Link} = Router;
pulls out the property Link
from the default export , assuming it is an object, eg从默认导出中拉出属性
Link
,假设它是一个对象,例如
export default {
Link: 42
};
(the default export is actually nothing but a standardized named export with the name "default"). (默认导出实际上只是一个名为“default”的标准化命名导出)。
See also export
on MDN .另请参阅MDN 上的
export
。
Complete example:完整示例:
// react-router.js
export const Link = 42;
export default {
Link: 21,
};
// something.js
import {Link} from './react-router';
import Router from './react-router';
const {Link: Link2} = Router;
console.log(Link); // 42
console.log(Link2); // 21
With Babel 5 and below I believe they have been interchangeable because of the way ES6 modules have been transpiled to CommonJS.在 Babel 5 及以下版本中,我相信它们是可以互换的,因为 ES6 模块已被转换为 CommonJS。 But those are two different constructs as far as the language goes.
但就语言而言,这是两种不同的结构。
To do this:去做这个:
import {purple, grey} from 'themeColors';
Without repeating export const
for each symbol , just do:无需为每个符号重复
export const
,只需执行以下操作:
export const
purple = '#BADA55',
grey = '#l0l',
gray = grey,
default = 'this line actually causes an error';
Except for different exports, it may also lead to different bundled code by WebPack when using two variant ways to destruct ESM modules:除了导出不同外,在使用两种变体方式破坏 ESM 模块时,也可能导致 WebPack 捆绑的代码不同:
Destruct within the import
statement:在
import
语句中进行破坏:
import {Link} from 'react-router'; Link('1'); Link('2');
// WebPack output var util_mobileValidator__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1); (0,util_mobileValidator__WEBPACK_IMPORTED_MODULE_3__.Link)('1'); (0,util_mobileValidator__WEBPACK_IMPORTED_MODULE_3__.Link)('2');
Use destructuring syntax:使用解构语法:
import Router from 'react-router'; const {Link} = Router; Link('1'); Link('2');
// WebPack output: var util_mobileValidator__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1); const {Link} = util_mobileValidator__WEBPACK_IMPORTED_MODULE_3__; Link(1); Link(2);
As you can see in the output example above where there is redundant code, which is not good for optimization when trying to uglify via UglifyJS
, or Terser
.正如您在上面的 output 示例中看到的那样,其中存在冗余代码,当尝试通过
UglifyJS
或Terser
进行 uglify 时,这不利于优化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.