首页 > 解决方案 > 不能在模块外使用导入

问题描述

我目前正在将我的不和谐机器人从 JavaScript 重写为 TypeScript。这样做时我遇到了 SyntaxError: Cannot use import statement outside a module。从其他问题看来,添加"type" : "module",应该package.json可以解决它。但是,这会导致另一个 TypeError: Unknown file extension ".ts"

解决此问题的正确方法是什么,以便我可以在index.ts和其他文件中使用导入语句?

索引.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);

包.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"]
}

标签: node.jstypescriptes6-modules

解决方案


好吧,看来您只是在运行node .或像那样运行您的 ts 代码。问题是,节点要运行 js 文件,这就是 ts 无法识别的原因。

因此,要解决此问题,您可以安装ts-node,并在其中添加运行命令package.json

npm i ts-node -D

"scripts": {
  "start": "ts-node index.ts"
}

npm run start


推荐阅读