Dav*_*ton 23 javascript es6-modules
我见过 在 CommonJS Node 应用程序中导入 ES6 模块? 如何将 ES6 模块与 commonjs 和https://nodejs.org/api/esm.html#esm_enabling一起使用
我还是不明白。对 javascript 相当陌生。
基本问题是“我需要做什么以及这些位在哪里才能使我能够在 CommonJS 中使用 ES6 模块?
Mik*_*keM 29
在 Node.js 中,如果要在 CommonJS 模块中导入 ES 模块,可以在 ES 模块上使用动态import和.mjs文件扩展名。例如:
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!"
);
Run Code Online (Sandbox Code Playgroud)
mod.mjs ES 模块
export const msg = "Hello world!";
Run Code Online (Sandbox Code Playgroud)
两个示例说明如何import在 CommonJS 模块中使用来导入全部或部分包lodash-es:
export const msg = "Hello world!";
Run Code Online (Sandbox Code Playgroud)
import('lodash-es').then(_ => {
console.log(_.pad(_.toUpper('hello world'), 17, '*'));
});
Run Code Online (Sandbox Code Playgroud)
或者您可以将您需要的内容导入到不同的 CommonJS 模块中,然后导出Promise您可以import或require.
实用程序.js
Promise.all([
import('lodash-es/pad.js'),
import('lodash-es/toUpper.js'),
])
.then(([{ default: pad }, { default: toUpper }]) => {
console.log(pad(toUpper('hello world'), 17, '#'));
});
Run Code Online (Sandbox Code Playgroud)
索引.js
module.exports = Promise.all([
import('lodash-es/pad.js'),
import('lodash-es/toUpper.js'),
]);
Run Code Online (Sandbox Code Playgroud)
ESModules 和 CommonJS 是互斥的,所以你不能“在 CommonJS 中使用 ES6 模块”。
然而,在某种程度上,你可以“在 ESModules 中使用 CommonJS”,如果“CommonJS”仅指的是函数require()。require()您可以使用以下命令创建函数实例module.createRequire():
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
// sibling-module.js is a CommonJS module.
const siblingModule = require('./sibling-module');
Run Code Online (Sandbox Code Playgroud)
NodeJS 的文档中有一个章节介绍了两个模块系统之间的互操作性。这非常有帮助,您可能想检查一下。
| 归档时间: |
|
| 查看次数: |
36011 次 |
| 最近记录: |