我一直在使用 Node.js 时遇到问题。
这是相关代码(app.ts
):
const express = require("express");
const auth = require("./service/auth");
import { Request, Response } from "express";
import User from "./model/User";
import con from "./config/db";
const port = 3000;
const app = express();
app.use(express.json());
...
我得到的错误是:
(node:16524) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
C:\Users\010bo\OneDrive\Documents\GitHub\rpg-backend\app\app.ts:4
import { Request, Response } from "express";
^^^^^^
SyntaxError: Cannot use import statement outside a module
at wrapSafe (internal/modules/cjs/loader.js:1117:16)
at Module._compile (internal/modules/cjs/loader.js:1165:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1221:10)
at Module.load (internal/modules/cjs/loader.js:1050:32)
at Function.Module._load (internal/modules/cjs/loader.js:938:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47
所以我寻找解决方案并发现:语法错误:无法在模块外部使用 import 语句 https://stackoverflow.com/questions/58384179/syntaxerror-cannot-use-import-statement-outside-a-module
这告诉我:
将 "type": "module" 添加到最近的父 package.json
So add "type": "module"
到 package.json。我现在得到的输出是:
internal/modules/run_main.js:54
internalBinding('errors').triggerUncaughtException(
^
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for C:\Users\010bo\OneDrive\Documents\GitHub\rpg-backend\app\app.ts
[90m at Loader.defaultGetFormat [as _getFormat] (internal/modules/esm/get_format.js:65:15)[39m
[90m at Loader.getFormat (internal/modules/esm/loader.js:98:42)[39m
[90m at Loader.getModuleJob (internal/modules/esm/loader.js:227:31)[39m
[90m at async Loader.import (internal/modules/esm/loader.js:161:17)[39m {
code: [32m'ERR_UNKNOWN_FILE_EXTENSION'[39m
}
于是我又上网寻找解决办法,发现:无法运行我的 Node.js Typescript 项目 TypeError [ERR_UNKNOWN_FILE_EXTENSION]:/app/src/App.ts 的未知文件扩展名“.ts” https://stackoverflow.com/questions/62096269/cant-run-my-node-js-typescript-project-typeerror-err-unknown-file-extension
这告诉我:
从 package.json 中删除 "type": "module"
所以我认为我发现自己陷入了第 22 条军规的境地。我不知道下一步该去哪里。
我也尝试了其他解决方案语法错误:无法在模块外部使用 import 语句 https://stackoverflow.com/questions/58384179/syntaxerror-cannot-use-import-statement-outside-a-module
使用 .mjs 扩展名显式命名文件。所有其他文件(例如 .js)将被解释为 CommonJS,如果 package.json 中未定义类型,则这是默认值。
这不起作用,要么给我相同的错误,要么给我不同的语法错误,我认为是因为我使用的是打字稿。
预先感谢任何可以提供帮助的人。