node.js - Ako nakonfigurovať TS, aby povoľoval importy z CJS do ES modulov (node-fetch a Express)?


Snažím sa spustiť dve knižnice v jednom projekte: fetch-node, ktorá je ES modul, a Express, ktorý je CommonJS. Problém je v tom, že musím importovať fetch-node takto:

import fetch from 'node-fetch';

ale Express odo mňa vyžaduje, aby som ho importoval takto:

const express = require('express')

čo nie je možné s mojou konfiguráciou, package.json: "type": "module", a tsconfig.json:

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

Takže keď importujem Express tak, ako je popísané, dostanem túto chybu:

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.

Aký je tu trik? Nemôžem tieto dve knižnice použiť spolu v jednom projekte?

Odpoveď č. 1

Problém, ktorému som čelil, naozaj pochádzal z tsconfig. Musel som pridať:

"moduleResolution": "node", 

aby bolo možné používať ako require(), tak aj dynamický import ako import * from "asdf"