node.js - Làm thế nào để cấu hình TS cho phép nhập khẩu từ CJS sang các module ES (node-fetch & Express)?
Tôi đang cố gắng để hai thư viện chạy trong cùng một dự án: fetch-node, là một mô-đun ES, và Express, là CommonJS. Vấn đề là tôi phải import fetch-node như sau:
import fetch from 'node-fetch';
nhưng Express yêu cầu tôi phải nhập nó như sau:
const express = require('express')
điều này không khả thi với cấu hình của tôi, package.json: "type": "module", và tsconfig.json:
"target": "es2016",
"lib": ["es2019"],
"module": "Node16",
"esModuleInterop": true,
Vậy khi tôi nhập Express như đã mô tả, tôi nhận được lỗi này:
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.
Mánh khóe ở đây là gì? Tôi không thể sử dụng hai thư viện này cùng nhau trong một dự án sao?
Câu trả lời #1
Vấn đề mà tôi đang gặp phải thực sự xuất phát từ tsconfig. Tôi đã phải thêm:
"moduleResolution": "node",
có thể sử dụng cả require() và import động như import * from "asdf"
