gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 02:05:10 27 4
gpt4 key购买 nike

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

ma​​in.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 扩展名,请遵循 Node 可执行文件本身给出的建议。

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

关于node.js - 如何在 Node.js 的同一个文件中使用 ES6 导入和 CommonJS 导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63790688/

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