2017-04-22 32 views
0

Person.tsを失敗typescriptです単純なモジュールの例は

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 
+0

は、ブラウザがcommonjsについて知らないこのコメント http://stackoverflow.com/a/33294807/4096589 を見ますモジュール – radix

+0

どのブラウザをお使いですか?多分あなたはpolyfillを見逃しているでしょう:) – Digvijay

答えて

1

私のソリューションは、この回答に基づいています。https://stackoverflow.com/a/36769278/1977315

  1. npm install requirejs 
    
  2. はhtmlページ

    でrequireJsを含めるrequireJsをインストール
    <h1 id="h1"></h1> 
    <script src="../node_modules/requirejs/require.js" data-main="test.js"></script> 
    
  3. モジュールAMDの引数を持つコードをコンパイル:

    tsc -module amd 
    
0

アプリをブラウザと互換性のあるものにする必要があります。 WebPACKのを使用して、たとえば :

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

活字コンパイルはブラウザでは動作しませんどのcommonjsモジュールの分解能、 であなたのファイルをコンパイルします

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

とあなたのhtmlに(nodejsはcommonjsを使用しています)。 Webpackは、あなたにアプリを連れてブラウザを準備させるバンドラの例です。

0

transpiledコードは以下の通りです:

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; 
 
}());

+0

残念ながら、モジュールはCommonJS –

関連する問題