【发布时间】:2021-12-15 09:29:44
【问题描述】:
所以,我正在使用 Node16/Typescript 并尝试导入 discord.js。
我想使用import 语法,而不是require,因为我更习惯了,而且还会导致 TS 自动添加我导入的类型。
但遗憾的是,它是如此的混乱,而且有太多的 import/require 语法,我永远不知道该怎么做。
所以我这样做了:
import dotenv from 'dotenv';
import { Client, Intents } from 'discord.js';
使用简单的 tsconfig
"target": "es2020"
"module": "es2020"
"moduleResolution": "node"
但是当我运行我的代码时它失败了。
TypeError:无法读取未定义的属性(读取“minLength”) 在 file:///C:/Users/xxxx/Documents/Repository/xxxx/node_modules/@discordjs/builders/dist/index.mjs:1:831 在 ModuleJob.run (节点:内部/模块/esm/module_job:185:25) 在异步 Promise.all(索引 0) 在异步 ESMLoader.import (node:internal/modules/esm/loader:281:24) 在异步加载ESM(节点:内部/进程/esm_loader:88:5) at async handleMainPromise (node:internal/modules/run_main:65:12)
我知道discord.js 被导出为commonJs,所以我改用require。
现在代码可以工作了,但是找不到我导入的类型,并且 eslint 抱怨
要求语句不是导入语句的一部分。
我尝试了所有其他 import / require 解决方案,但仍然没有任何效果,要么它需要 package.json 中的 type : module 但代码不起作用,要么 ts 抱怨我如何导入东西......
基本上如果我使用我想要的方式
import { Client, Intents } from 'discord.js'; 代码不工作,但编译器和 VsCode 自动完成所有内容并知道类型(并且 eslint 没有错误)
const Discord = require('discord.js'); 将没有类型,eslint 会抱怨,但代码会工作......
我该怎么办?
【问题讨论】:
标签: javascript node.js typescript