【问题标题】:Cannot use import outside of a module不能在模块外使用导入
【发布时间】: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


【解决方案1】:

看来您只是在运行 node . 或类似的东西来运行您的 ts 代码。问题是,node要运行js文件,这就是ts无法识别的原因。

所以要解决这个问题,可以安装ts-node,并在package.json中添加运行命令

npm i ts-node -D

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

npm run start

【讨论】:

    猜你喜欢
    • 2021-09-16
    • 2021-09-01
    • 2020-07-14
    • 2020-04-15
    • 2021-02-06
    • 2021-07-05
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    相关资源
    最近更新 更多