typescript - 简单模块示例失败

typescript - simple module example fails

Person.ts:

export class Person {
  private _name: string;
  constructor(name: string) {
    this._name = name;
  }
  get name(): string {return this._name};
}

test.ts:

import {Person} from "./Person";

var user = new Person("John");
document.getElementById("h1").innerHTML = user.name;

tsconfig.json:

{
  "compilerOptions": {
    "target": "es5"
    ,"outDir" : "build"
  }
}

打开 Chrome 中的结果时,控制台上显示以下错误:

Uncaught ReferenceError: exports is not defined
at test.js:2

您需要使您的应用与浏览器兼容。 例如使用 webpack:

> npm install webpack -g
> webpack build/test.js bundle.js

在你的 html

<script src="/bundle.js"></script>

Typescript 编译将使用 commonjs 模块解析编译您的文件, 这在浏览器中不起作用(nodejs 使用 commonjs)。 Webpack 是一个捆绑器的例子,它将带你的应用程序并使其浏览器就绪。

转译代码如下:

define(["require", "exports"], function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var Person = (function () {
        function Person(name) {
            this._name = name;
        }
        Object.defineProperty(Person.prototype, "name", {
            get: function () { return this._name; },
            enumerable: true,
            configurable: true
        });
        ;
        return Person;
    }());
    exports.Person = Person;
});

然而,如果您看到这需要浏览器理解模块系统,在本例中是 requirejs。如果你愿意,你可以直接使用代码片段 - 它是完美的 ES5 代码。

var Person = (function() {
  function Person(name) {
    this._name = name;
  }
  Object.defineProperty(Person.prototype, "name", {
    get: function() {
      return this._name;
    },
    enumerable: true,
    configurable: true
  });;
  return Person;
}());

我的解决方案基于这个答案:

  1. 安装requireJs

    npm install requirejs
    
  2. 在 html 页面中包含 requireJs

    <h1 id="h1"></h1>
    <script src="../node_modules/requirejs/require.js" data-main="test.js"></script>
    
  3. 使用模块 amd arg 编译代码:

    tsc -module amd