网站搜索

node.js - 如何配置 TS 以允许从 CJS 导入到 ES 模块(node-fetch & Express)?


我正在尝试在一个项目中运行两个库:fetch-node,它是一个 ES 模块,以及 Express,它是 CommonJS。问题是我必须像这样导入 fetch-node:

import fetch from 'node-fetch';

但是 Express 需要我像这样导入它:

const express = require('express')

在我的配置中这是不可能的,package.json:"type": "module", 和 tsconfig.json:

"target": "es2016",   
"lib": ["es2019"],    
"module": "Node16",    
"esModuleInterop": true,

所以当我按照描述导入 Express 时,我收到这个错误:

const express = require('express');
                ^

ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and '/mnt/c/Users/Johannes/citygmlToGltf/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
    at file:///mnt/c/Users/Johannes/citygmlToGltf/bin/app.js:15:17
    at ModuleJob.run (node:internal/modules/esm/module_job:194:25)

Node.js v19.1.0
error Command failed with exit code 1.

这里的诀窍是什么?我能不能在一个项目中同时使用这两个库?

答案#1

我遇到的问题确实来自 tsconfig。我必须添加:

"moduleResolution": "node", 

能够同时使用 require() 和动态导入,如 import * from "asdf"