2017-04-22 28 views
0

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" 
    } 
} 

當在瀏覽器打開所述結果,控制檯上顯示以下錯誤:

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

看到此評論 http://stackoverflow.com/a/33294807/4096589 瀏覽器不知道CommonJS的模塊 – radix

+0

您正在使用哪種瀏覽器?也許你錯過了一個polyfill :) – Digvijay

回答

1

我的解決方案是基於這樣的回答:https://stackoverflow.com/a/36769278/1977315

  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 
    
0

您需要使您的應用與瀏覽器兼容。 例如使用的WebPack:

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

,並在你的HTML

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

打字稿編譯將編譯CommonJS的模塊分辨率, 您的文件,不會在瀏覽器中工作(使用的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 –