简体   繁体   English

如何在 CommonJS 中使用 ES6 模块?

[英]How to use ES6 modules in CommonJS?

I've seen Importing ES6 modules in CommonJS Node app?我见过在 CommonJS Node 应用程序中导入 ES6 模块? How to use ES6 modules with commonjs and https://nodejs.org/api/esm.html#esm_enabling 如何使用 ES6 模块与 commonjshttps://nodejs.org/api/esm.html#esm_enabling

And I still don't get it.我还是不明白。 Fairly new to javascript. javascript 相当新。

The fundamental question is "What do I need to do and where do the bits go that enable me to use ES6 modules inside CommonJS?最基本的问题是“我需要做什么以及使我能够在 CommonJS 中使用 ES6 模块的 go 位在哪里?

In Node.js, if you want to import an ES module in a CommonJS module you can use dynamic import and the .mjs file extension on the ES modules.在 Node.js 中,如果您想在 CommonJS 模块中导入 ES 模块,您可以在 ES 模块上使用动态import.mjs文件扩展名。 For example:例如:

index.js CommonJS index.js CommonJS

const crypto = require('crypto');  // to show this is a commonJS module

import('./path/to/mod.mjs').then(mod =>
  console.log(mod.msg);    //  "Hello world!"
);

mod.mjs ES module mod.mjs ES 模块

export const msg = "Hello world!";

Adding "type": "module" to the package.json enables ES 6 module."type": "module"添加到 package.json 启用 ES 6 模块。 So in your package.json file add "type": "module" (or change it from "type": "commonjs" ).因此,在您的 package.json 文件中添加"type": "module" (或将其从"type": "commonjs"更改)。 Changing this will enable ES6 modules and allow your source code to use import syntax.更改此设置将启用 ES6 模块并允许您的源代码使用导入语法。

ESModules and CommonJS are mutually exclusive, so you can't "use ES6 modules inside CommonJS". ESModules 和 CommonJS 是互斥的,所以你不能“在 CommonJS 中使用 ES6 模块”。

However, in a way, you can "use CommonJS inside ESModules", if by "CommonJS" you only mean the require() function.但是,在某种程度上,您可以“在 ESModules 中使用 CommonJS”,如果“CommonJS”仅表示require() function。 You can create an instance of require() function with module.createRequire() :您可以使用module.createRequire()创建require() function 的实例:

import { createRequire } from 'module';
const require = createRequire(import.meta.url);

// sibling-module.js is a CommonJS module.
const siblingModule = require('./sibling-module');

There's a chapter in NodeJS's documentation on interoperability between the two module systems . NodeJS 的文档中有一章是关于 两个模块系统之间的互操作性的 It's very helpful, you might want to check it out.这很有帮助,您可能想检查一下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM