gpt4 book ai didi

javascript - SyntaxError : Cannot use import statment without a module, 类型错误 [ERR_UNKNOWN_FILE_EXTENSION]:Catch 22

转载 作者:行者123 更新时间:2023-12-03 12:13:17 25 4
gpt4 key购买 nike

我一直有 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
所以我寻找解决方案并找到:
SyntaxError: Cannot use import statement outside a module
这告诉我:

Add "type": "module" to the nearest parent package.json


所以添加 "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
}
于是我再次上网,寻找解决方案,发现: Can't run my Node.js Typescript project TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /app/src/App.ts
这告诉我:

Remove "type": "module" from package.json


所以我想我已经发现自己处于第 22 条问题的境地。我不确定下一步该去哪里。
我还尝试了 SyntaxError: Cannot use import statement outside a module 中的其他解决方案

Explicitly name files with the .mjs extension. All other files, such as .js will be interpreted as CommonJS, which is the default if type is not defined in package.json.


这不起作用,要么给我同样的错误,要么给我一个不同的语法错误,我认为是因为我使用的是 typescript 。
提前感谢任何可以提供帮助的人。

最佳答案

const { Request, Response } = require("express")
其他的也一样。

关于javascript - SyntaxError : Cannot use import statment without a module, 类型错误 [ERR_UNKNOWN_FILE_EXTENSION]:Catch 22,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62792310/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com