网站搜索

webpack - 如何在 TypeScript 模块中使用全局对象上的库(无需导入它)?


我正在编写一个用户脚本,该脚本的依赖项由用户脚本插件注入。我绝不能导入任何库,我只想要类型。在添加TS之前,JS代码是可以正常工作的。

示例:

R.range(0, 3)

使 TypeScript 编译器崩溃于

'R' refers to a UMD global, but the current file is a module. Consider adding an import instead.

我尝试过

/// <reference path="../../node_modules/@types/ramda/index.d.ts"/>

但不起作用——编译器仍然拒绝可运行的代码。

我也尝试在使用 import 语句时将其添加到 webpack 配置中的 externals。但没用:

Uncaught TypeError: Cannot read property 'range' of undefined

仅导入类型不起作用:

import type R from 'ramda';

->

TS1361: 'R' cannot be used as a value because it was imported using 'import type'.

我也尝试过手动将它放到全局对象上:

import type R from 'ramda';

declare global {
  // neither working
  const R = R;
  const R: R;
}

所以,我的问题是:

为什么在 Ramda 上不起作用,而 jQuery 却可以正常工作(全局变量无需导入)?

如何只“导入”Ramda 的类型,即全局 R 变量,而不导入(打包)整个库的源代码?

答案#1

解决了,那种命名空间的东西让我感到困惑...

放

import type R from 'ramda';

declare global {
  const R: typeof R;
}

在 ramda.d.ts 中,并且 R 应该可以从任何地方访问。