且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将基于IIFE的JavaScript模块导入Angular TypeScript应用程序?

更新时间:2023-11-22 17:40:22

您可以在TypeScript中包装第三方SDK模块使用 eval 的hack。

You can wrap the third-party SDK in a TypeScript module using a hack with eval.

假设ThirdPartySDK.js如下所示:

Let's say that ThirdPartySDK.js looks like this:

var ThirdPartySDK = (function () {
    var exports = {
        foo: function () { console.log("Hello, world!"); }
    };
    return exports;
})();

然后,您将创建一个类似于此的ThirdPartySDK-wrapper.ts模块:

You would then create a ThirdPartySDK-wrapper.ts module that looks something like this:

import * as fs from 'fs';
const script = fs.readFileSync('../lib/ThirdPartySDK.js').toString();

global.eval(script);

//@ts-ignore
export default ThirdPartySDK;

@ ts-ignore 指令是必需的防止TypeScript编译器抱怨没有找到 ThirdPartySDK 变量的声明(它在通过 eval $ c $执行的脚本中声明c>)。

The @ts-ignore directive is required to keep the TypeScript compiler from complaining about not finding a declaration for the ThirdPartySDK variable (it is declared in the script executed through eval).

然后你可以通过包装模块导入ThirdPartySDK:

You can then import ThirdPartySDK through the wrapper module:

import ThirdPartySDK from './wrapper';
ThirdPartySDK.foo();  // Console output: "Hello, world!" 

请注意,此包装器仅适用于在Node.js中运行的应用程序,因为它使用 fs.fileReadSync 获取脚本的内容。

Note that this wrapper only works for applications running in Node.js, since it uses fs.fileReadSync to get the contents of the script.

如果您打算在浏览器中使用它,您将需要一些其他方法来检索脚本。您可以使用WebPack等框架将ThirdPartySDK脚本捆绑为一个字符串值,您可以在包装器模块中 require

If you're going to use it in a browser, you will need some other way to retrieve the script. You could probably use frameworks such as WebPack to bundle the ThirdPartySDK script as a string value that you can require in the wrapper module.