【问题标题】:How to use ES6 imports and CommonJS imports in the same file in Node.js如何在 Node.js 的同一个文件中使用 ES6 导入和 CommonJS 导入
【发布时间】:2020-12-26 15:35:17
【问题描述】:

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

ma​​in.js

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

这可能吗?

【问题讨论】:

    标签: node.js express babeljs es6-modules commonjs


    【解决方案1】:

    文档:

    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.`
    

    【讨论】:

      猜你喜欢
      • 2016-08-31
      • 2021-11-27
      • 2017-12-23
      • 2018-04-21
      • 1970-01-01
      • 1970-01-01
      • 2022-08-10
      相关资源
      最近更新 更多