使用System.js导入Typescript编译的模块时出错

时间:2017-02-05 07:21:54

标签: javascript typescript systemjs

我最近学习使用system.js导入由Typescript编译的模块。这些模块以前是为require.js编译的,工作正常。

但是,在合并到system.js时,在应用 system-production.js 时无法导入模块。控制台说

Uncaught (in promise) Error: Module instantiation did not call an anonymous or correctly named System.register.
   Instantiating https://www.star.com/libs/js/klondike.js
   Loading ./libs/js/klondike.js
    at register-loader.js:203
t           @ common.js:83
(anonymous) @ loader-polyfill.js:70

我不太清楚导致错误消息的原因。当我应用 system.src.js 时,不会出现错误消息,但我无法在导入的模块中使用函数。任何调用都将返回undefined。那么我的运作方式是否错误?

以下是源代码。

的test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
</body>

<!-- sys import -->
<script src="libs/js/system-production.js"></script>

<!--<script src="libs/js/system.src.js"></script>-->

<script>
    System.import("./libs/js/klondike.js");
</script>

</html>

tsconfig.json

{
  "compilerOptions": {
    "module": "System",
    "outFile": "../../js/klondike.js",
    "target": "es5",
    "sourceMap": true,
    "removeComments": true
  },
    "include": [
    "./*"
  ]
}

主要模块:CardMoves.ts

//sys import
import * as DBJSN from "./debugJson";
import PokerCard from "./Cards";

let suits: string[] = ["spade", "heart", "club", "diamond"];
let cards: string[] = [, "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];

//sys export
export function createDeck() {
    let playCards: PokerCard[] = new Array(DBJSN.settings.decks*52);

    console.log(playCards);

    for (let i=0; i<playCards.length; i++) {
        playCards[i] = new PokerCard();
        playCards[i].suit = suits[Math.floor(i % 52 / 13)];
        playCards[i].card = i % 52 % 13 + 1;
    }

    return playCards;
}

Dependency1:Cards.ts

//sys export
export default class PokerCard {
    private _suit: string;
    private _card: number;

    constructor() {}

    //Suit getter and setter
    get suit(): string {
        return this._suit;
    }

    set suit(newSuit: string) {
        try {
            if (this._suit === undefined)
                this._suit = newSuit;
            else
                throw "Suit value has been set.";
        }
        catch(e) {
            console.log(e);
        }
    }

    //Card getter and setter
    get card(): number {
        return this._card;
    }

    set card(newCard: number) {
        try {
            if (this._card === undefined)
                this._card = newCard;
            else
                throw "Card value has been set.";
        }
        catch(e) {
            console.log(e);
        }
    }
}

Dependency2:debugJson.ts

//sys export
export let settings = {
    decks: 1,
    cardsPerClick: 1,
    timer: true
};

1 个答案:

答案 0 :(得分:2)

我有同样的问题。问题是我试图使用bundle作为常规模块。根据文档包应该有几个System.register调用。然后,您必须通过脚本标记将此捆绑包添加为常规js文件。然后调用你的起点模块(我假设你的情况下是createDeck)。

请点击https://github.com/systemjs/systemjs/blob/master/docs/production-workflows.md了解详情。

希望这有帮助!