typescript 如何配置TS以允许从CJS导入到ES模块(节点获取与快速)?

cetgtptt  于 2022-11-26  发布在  TypeScript
关注(0)|答案(1)|浏览(243)

我尝试在一个项目中运行两个库: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.

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

fiei3ece

fiei3ece1#

我所面临的问题确实来自于tsconfig。我不得不补充:

"moduleResolution": "node",

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

相关问题