【发布时间】:2021-12-20 17:24:28
【问题描述】:
我目前正在将我的 discord 机器人从 JavaScript 重写为 TypeScript。这样做时我遇到了 SyntaxError:Cannot use import statement outside a module。从其他问题看来,在package.json 中添加"type" : "module", 应该可以解决它。但是这会导致另一个 TypeError:Unknown file extension ".ts"。
解决此问题的正确方法是什么,以便我可以在 index.ts 和其他文件中使用导入语句?
index.ts:
import {Client, Intents} from "discord.js";
import dotenv from "dotenv";
dotenv.config();
const token = process.env.TOKEN;
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
client.once('ready', () => {
console.log('Ready!');
});
client.login(token);
package.json:
{
"name": "wdr",
"version": "1.0.0",
"description": "A discord bot",
"main": "index.ts",
"type" : "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "wdr",
"license": "ISC",
"dependencies": {
"@discordjs/rest": "^0.1.0-canary.0",
"discord-api-types": "^0.24.0",
"discord.js": "^13.3.1",
"dotenv": "^10.0.0"
}
}
tsconfig.json:
{
"compilerOptions": {
"lib": ["ESNext"],
"target": "ESNext",
"module": "commonjs",
"moduleResolution": "Node",
"strict": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true
},
"include": [
"index.ts",
"commands/*.ts"
],
"exclude": ["node_modules"]
}
【问题讨论】:
-
我认为你的编译选项是问题所在。它的说模块:commonjs。
-
分享你的 ts 配置
-
@Tiko tsconfig.json 在那里。
-
直接
include整个*.ts不是更好吗? -
刚刚解决了这个问题。然而,错误仍然存在。
标签: node.js typescript es6-modules