如何在Node.js的同一文件中使用ES6导入和CommonJS导入

问题描述

我遇到了有关如何使用Babel在Node.js中使用ES6导入的教程,但是后来Commonjs导入不起作用。我想在Node.js(Express.js)的同一文件中使用ES6导入和Commonjs导入。

main.js

const jsdom = require("jsdom");
import {GotRequestFunction} from 'got';

这可能吗?

解决方法

文档:

  1. Differences between ES modules and CommonJS
  2. module.createRequire(filename)
import { createRequire } from 'module';
const require = createRequire(import.meta.url);

import { A } from "./A.mjs" // NB: .mjs extention
console.log(A) // it works

const fs = require('fs')
console.log(fs) // it works as well

如果您不喜欢.mjs扩展名,请遵循节点可执行文件本身提供的建议。

`Warning: To load an ES module,set "type": "module" in the package.json or use the .mjs extension.`

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...