如何将基于IIFE的JavaScript模块导入Angular TypeScript应用程序? [英] How do I import an IIFE-based JavaScript module into an Angular TypeScript app?

查看:139
本文介绍了如何将基于IIFE的JavaScript模块导入Angular TypeScript应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个第三方SDK作为基于oldschool IIFE的模块编写。换句话说,它看起来像这样:

So I have a third-party SDK written as an oldschool IIFE based module. In other words it looks something like this:

var ThirdPartySDK = (function() {
  var export = {};

  // Add some methods to export

  return export;
})();

然后,您可以通过在全局范围内引用它来使用它,如下所示:

You would then be expected to use it by referencing it on the global scope like this:

<html>
  <body>
    <script src="lib/ThirdPartySDK.js">
    <script>
      ThirdPartySDK.foo();
    <\script>
  <\body>
<\html>

我当然可以用这种方式使用它,但这确实是使用Angular和TypeScript的最佳实践?有没有办法用angular / TypeScript / webpack进行设置,以便我可以使用正确的import语句?这样的事情:

I could still use it this way of course, but is that really the best practice with Angular and TypeScript? Is there some way to set things up with angular/TypeScript/webpack so that I can use a proper import statement? Something like this:

import { ThirdPartySDK } from '../lib/ThirdPartySDK.js';
ThirdPartySDK.foo();


推荐答案

您可以在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 )。

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.

这篇关于如何将基于IIFE的JavaScript模块导入Angular TypeScript应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆