首页 > 解决方案 > 如何导入具有 nodejs 16 类型的模块?

问题描述

所以,我正在使用 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:无法在文件:///C:/Users/xxxx/Documents/Repository/xxxx/node_modules/@discordjs/builders/dist/index.mjs:1:831 在 ModuleJob 读取未定义的属性(读取“minLength”) .run (node:internal/modules/esm/module_job:185:25) at async Promise.all (index 0) at async ESMLoader.import (node:internal/modules/esm/loader:281:24) at async loadESM ( node:internal/process/esm_loader:88:5) 在异步 handleMainPromise (node:internal/modules/run_main:65:12)

我知道discord.js是作为 commonJs 导出的,所以我require改用了。

现在代码可以工作了,但是找不到我导入的类型,并且 eslint 抱怨

要求语句不是导入语句的一部分。

我尝试了所有其他 import / require 解决方案,但仍然没有任何效果,要么它需要type : module在 package.json 但代码不起作用,要么 ts 抱怨我如何导入东西......

基本上,如果我使用我希望 import { Client, Intents } from 'discord.js';代码 don7t 工作的方式,但编译器和 VsCode 会自动完成所有内容并知道类型(并且 eslint 没有错误)

const Discord = require('discord.js');将没有类型,eslint 会抱怨,但代码会工作......

我应该怎么办 ?

标签: javascriptnode.jstypescript

解决方案


目标意味着打字稿被编译到该目标。通常我们为此使用 es2015 来最大化支持的平台。你想要的是lib.

"target": "es2015",
"lib": ["es2020"]

推荐阅读