首页 > 解决方案 > 如何从 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"/>

这不起作用 - 编译器仍然拒绝工作代码。

我还尝试在使用语句时将其添加到externalswebpack 配置中。import那没有用:

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,而不导入(捆绑)整个库的源代码?

标签: typescriptwebpacktypescript-typingsramda.js

解决方案


解决了,那个命名空间的事情让我很困惑......

import type R from 'ramda';

declare global {
  const R: typeof R;
}

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


推荐阅读