javascript - 如何导入具有 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 会抱怨,但代码会工作......
我应该怎么办 ?
解决方案
目标意味着打字稿被编译到该目标。通常我们为此使用 es2015 来最大化支持的平台。你想要的是lib
.
"target": "es2015",
"lib": ["es2020"]
推荐阅读
- migration - 如何在 2 个实例之间迁移 Apache Druid 数据?
- excel - 使用任何算法在 word 中混淆 vba 宏
- android - 如何使用 Android Camera2 API 访问 ImageReader 队列中的所有图像
- angular - 运行项目时出现fireStore错误
- sql - SQL Server Sum 特定交易类型金额
- symfony - 如何使用 Doctrine ORM 处理 MariaDB 系统版本表?
- javascript - 有什么方法可以在带有目的地的文本中添加大纲,以便可以在 ng2-pdf-viewer 的 getOutline 中查看
- javascript - 如何在 Appium 中使用 JavascriptExecutor
- eclipse - 如何创建适用于与模式匹配的所有脚本文件的 eclipse 运行配置?
- javascript - JQuery Datatable通过点击获取行数据