问题描述
我遇到了有关如何使用Babel在Node.js中使用ES6导入的教程,但是后来Commonjs导入不起作用。我想在Node.js(Express.js)的同一文件中使用ES6导入和Commonjs导入。
main.js
const jsdom = require("jsdom");
import {GotRequestFunction} from 'got';
这可能吗?
解决方法
文档:
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.`