将 SweetAlert2 与 TypeScript 一起使用,找不到模块 'sweetalert2/dist/sweetalert2.js' 的声明文件

Using SweetAlert2 with TypeScript, could not find a declaration file for module 'sweetalert2/dist/sweetalert2.js'

我正在将我的一个项目迁移到 TypeScript,在该项目中使用了 SweetAlert2 库。

导入 SweetAlert2(JS 和 CSS)的默认方式是

import Swal from 'sweetalert2'

这适用于 TypeScript,因为库中有类型:https://github.com/sweetalert2/sweetalert2/blob/master/sweetalert2.d.ts

但是在我的项目中导入的方式是这样的:

import Swal from 'sweetalert2/dist/sweetalert2.js'

这只是 JS 导入,没有样式。使用这种类型的导入,我收到 TS 错误:

Could not find a declaration file for module 'sweetalert2/dist/sweetalert2.js'. 

ts(7016)

我试图将 sweetalert2/sweetalert2.d.ts 复制到 sweetalert2/dist/sweetalert2.d.ts,但出现另一个错误:

File 'node_modules/sweetalert2/dist/sweetalert2.d.ts' is not a module. 

ts(2306)

这是怎么回事,为什么 TS 抱怨 dist/sweetalert2.d.ts 不是模块?

SweetAlert 的当前类型定义不提供 "submodules" 的类型。 当您使用 declare module 语法 like this 时,您键入整个包 "at once"(用户从 ^sweetalert2$ 导入时得到的内容),但您没有描述包中的内容dist/ 中的各个编译文件,所以是的,它们不能明确定位。

尝试完全删除 copied 文件中的 declare module 块。然后,使用declare namespace Swal,就可以了。

我们应该可以修改 sweetalert2 的声明文件,这样简单导入和子文件导入都可以。

看看我是如何输入 graphql-compose 的,所以这成为可能:graphql-compose

每个 .js 文件都有一个对应的 .d.ts,不再有一个文件用 declare module.

描述整个模块

编辑:我在您的重现中尝试了这种方法,效果很好,我们也可以输入 sweetalert2.all.js。尽管以下解决方案可能更简单(文件更少,构建脚本更简单)。 1:1 映射方法更好,但可能更适合较大的库。

另一种可能性是将 declare module 'sweetalert2/dist/{**}' 条目添加到单个 sweetalert2.d.ts 文件,重新导出每个 dist/ 变体的默认模块内容:

declare module 'sweetalert2' {
    // Current contents of the file, unchanged
}

declare module 'sweetalert2/dist/sweetalert2.js' {
    export * from 'sweetalert2';
    // "export *" does not matches the default export, so do it explicitly.
    export { default } from 'sweetalert2';
}

declare module 'sweetalert2/dist/sweetalert2.all.js' {
    export * from 'sweetalert2';
    export { default } from 'sweetalert2';
}

我遇到了同样的问题,但我从您的链接中找到了解决方案 sweetalert2

遵循用法部分。

i was using in import SWAl from "sweetalert2/dist/sweetalert2.js".

它在新项目中工作,但不在我的旧项目中。所以我搬到这里并得到了我的解决方案。刚刚被 sweetalert2/dist/sweetalert2.js 替换为 sweetalert2

import Swal from 'sweetalert2';

大家也需要关注这一行。我从 sweetalert2 的 angular.json 文件中删除了 css 和 js。

检查这个步骤

projects -> architect -> test -> options -> styles:[] and scripts:[]