打字稿:从导入单独模块的UMD模块执行IIFE

时间:2019-02-15 19:34:52

标签: typescript iife

我有这样的tsconfig.json:

{
  "compilerOptions": {
    "lib": ["es2017", "dom"],
    "module": "umd",
    "outDir": "dist",
    "target": "es5",
    "declaration": true
  },
  "compileOnSave": true,
  "files": [
    "myClass.ts"
    "demo.ts"
  ]
}

我的打字稿,demo.ts

import { MyClass } from './myClass';

(() => {
  console.log('fired IIFE');
  document.onreadystatechange = function () {
    if (document.readyState === 'interactive') {
      console.log('hello world', MyClass);
    }
  };
})();

哪个被编译为:

(function (factory) {
    if (typeof module === "object" && typeof module.exports === "object") {
        var v = factory(require, exports);
        if (v !== undefined) module.exports = v;
    }
    else if (typeof define === "function" && define.amd) {
        define(["require", "exports", "./myClass"], factory);
    }
})(function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var myClass_1 = require("./myClass");
    (function () {
        console.log('fired IIFE');
        document.onreadystatechange = function () {
            if (document.readyState === 'interactive') {
                console.log('hello world', myClass_1.MyClass);
            }
        };
    })();
});

我的html:

<!DOCTYPE HTML>
<html>
<head>
  <title>Test</title>
  <script src="./dist/myClass.js"></script>
  <script src="./dist/demo.js"></script>
</head>
<body>
  <p>test</p>
</body>
</html>

我也尝试过:

<!DOCTYPE HTML>
<html>
<head>
  <title>Test</title>
</head>
<body>
  <p>test</p>
  <script src="./dist/myClass.js"></script>
  <script src="./dist/demo.js"></script>
</body>
</html>

两种方法都不会执行脚本,也不会打印任何日志语句。我在做什么错了?

1 个答案:

答案 0 :(得分:0)

原来,您需要使用requirejs才能执行由打字稿生成的UMD模块:

<!DOCTYPE HTML>
<html>
<head>
  <title>Test</title>
  <script data-main="dist/demo" type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.1/require.min.js"></script>
</head>
<body>
  <p>test</p>
</body>
</html>

这里发生的是data-main指向加载其他内容的.js文件。您不需要单独加载类脚本,require.js会为您完成。

这让我感到惊讶,因为使用gulp-wrap-umd软件包,它提供的包装器不会为封闭的脚本创建隔离范围,它实际上是全局的,而打字稿生成的UMD包装的脚本具有隔离范围。

在此实现中,我的引导脚本demo.js如下所示:

(function (factory) {
  if (typeof module === "object" && typeof module.exports === "object") {
      var v = factory(require, exports);
      if (v !== undefined) module.exports = v;
  }
  else if (typeof define === "function" && define.amd) {
      define(["require", "exports", "./myClass"], factory);
  }
})(function (require, exports) {
  "use strict";
  Object.defineProperty(exports, "__esModule", { value: true });
  require(["./dist/myClass"], (myClassModule) => {

    console.log('my class:', myClassModule.MyClass);
  });

在log语句所在的位置,您可以运行任何脚本,而无需document.onready...或window.onload。