如何使用 webpack 在打字稿中导入声明的全局变量

How to import declared global variable in typescript using webpack

我在导入已声明的全局变量时遇到问题。

在我们的网站上,我们有第三方框架,仅使用标签集成并在 window 上创建全局变量,例如 window.thirdParty。所以用法就像:thirdParty.methodOne() 我写的定义文件 third-party.d.ts 是这样的:

import { ITrirdPartyFramework } from './third-party-definitions/third-party-framework';

export interface ITrirdPartyFramework {
   methodOne():void,
}

然后我有一个文件(global-variables.ts),它定义了全局变量:

export declare const thirdParty: ITrirdPartyFramework;

最后我想在我的模块中使用它:

import { thirdParty } from './global-variables';

export const myFunction = () => {
    thirdParty.methodOne();
}

问题是 webpack 将定义编译为常规模块,在运行时出现错误,因为编译后的代码如下所示:

_global_variables__WEBPACK_IMPORTED_MODULE_3__["thirdParty"].methodOne();

而不是

thirdParty.methodOne();

你知道吗,如何告诉 webpack 忽略定义或如何处理这种情况?

您不必导入 *.d.ts 文件,它们是全局可见的。
您只能在这些文件中保留类型定义,而不能保留实现

接下来的步骤将解决您的问题:

  1. global-variables.ts 重命名为 global-variables。d.ts
  2. 全局变量中删除 export 关键字。d.ts
  3. 删除行 import { thirdParty } from './global-variables';