gpt4 book ai didi

javascript - 什么是 _interopRequireDefault ?

转载 作者:数据小太阳 更新时间:2023-10-29 04:31:43 25 4
gpt4 key购买 nike

我在this website上看到过解释那说:

_interopRequireDefault(): An ES6 CommonJS module is used as is (if it has a default export then it has a property named default). A normal CommonJS module becomes the value of the property default. In other words, in the later case, the module’s exports become the default export.

在代码中,往往会写几个_interopRequireDefault

所以如果我理解得很好,因为默认导出是整个文件上的一堆键/值作为一个整体导出,_interopRequireDefault 允许选择哪些模块将进入默认导出具体代码是什么呢?

最佳答案

允许您的代码使用为 Node.js 和 ES6 编写的模块。

模块在 ES6 和 CJS(通用 JS 规范)中的导出方式有所不同。

Common JS 中的模块:

module.exports = function () {};

ES6 中的模块:

export default function () {}

_interopRequireDefault 有一个相当简单的逻辑:

function _interopRequireDefault(module) {
const
isCJSModule = module && module.__esModule,
cjsStyedModule = { default: module };

return isCJSModule ? module: cjsStyedModule;
}

CJS 在 ES6 之前就存在了。 Node.js 仍然使用 CJS 版本和所有最初为 Node.js 编写的模块。

虽然 Node.js 现在实验性地支持 ES6 模块,但如果您使用 --experimental 标志运行并将模块文件命名为 .mjs

注意:现在在 2020 年,如果您在 中添加一个字段 "type": "module" ,Node.js 也支持带有 ES6 模块的 .js 文件包.json。在这里阅读更多:https://medium.com/@nodejs/announcing-core-node-js-support-for-ecmascript-modules-c5d6dc29b663

关于javascript - 什么是 _interopRequireDefault ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51159447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com