【问题标题】:Typescript One File Per ClassTypescript 每个类一个文件
【发布时间】:2015-07-17 14:13:36
【问题描述】:

我刚开始使用 Typescript,使用 Visual Studio 2015,但找不到在单独文件中使用类的方法。

在单个文件中,没有问题:

module someModule {
    export class TitleScreenState extends Phaser.State {
        game: Phaser.Game;
        constructor() {
            super();
        }
       //some code here
    }

    class GameRunningState extends Phaser.State {
        constructor() {
            super();
       //some code here
    }

    class SimpleGame {
        game: Phaser.Game;

         //some code here
        }

    }
}

    window.onload = () => {
        var game = new MyGame.Game();
    };

但是,当类被移动到它们自己的文件中时,它们没有显示错误,但在运行时我得到:

0x800a1391 - JavaScript 运行时错误:“MyGame”未定义

// app.ts

/// <reference path='Game.ts'/>
/// <reference path='StateTitleScreen.ts'/>
/// <reference path='StateGameRunning.ts'/>


    window.onload = () => {
        var game = new MyGame.Game();
    };


//----------------------------------------
// Game.s

module MyGame {
    export class Game {
    // some code here
}
  

//-----------------------------------------
// StateTitleScreen.ts
  
module MyGame {
    export class StateTitleScreen {
    // some code here
}
  
//-----------------------------------------
// StateGameRunning.ts
  
module MyGame {
    export class StateGameRunning {
    // some code here
}

【问题讨论】:

    标签: file class module namespaces typescript


    【解决方案1】:

    当您将代码拆分为多个文件时,您需要确保它们都在运行时加载。

    例如:

    <script src="Game.js"></script>
    <script src="StateTitleScreen.js"></script>
    <script src="StateGameRunning.js"></script>
    <script src="app.js"></script>
    

    请注意,您的app.js 在最后(因为它取决于其他人并且顺序很重要)。

    你也可以要求 TypeScript 为你提供一个文件:

    --out combined.js
    

    然后,您可以在页面上引用组合文件,而不是多个单独的文件 - 但您仍然可以通过在设计时拆分为多个文件来管理您的应用程序。

    【讨论】:

    • 谢谢。我喜欢将所有内容编译到单个文件的想法,但“--out combine.js”去哪里了?我以为是预编译命令行,结果报错9009。
    • 例如:tsc --out combined.js app.ts。大多数 IDE 都提供此选项。你用的是哪个编辑器?
    • 再次感谢史蒂夫。我正在使用 Visual Studio CE 2015。在项目的属性页面上,我找到了“将 javascript 输出合并到文件中”的复选框,可以在其中定义文件名。这行得通!虽然我从来没有找到可以使用 --out 选项的地方。
    • 该设置会自动为您应用--out 标志(事实上,该页面上的大多数设置最终都会向编译器发送标志)。
    猜你喜欢
    • 2018-04-26
    • 2010-09-06
    • 1970-01-01
    • 1970-01-01
    • 2016-06-14
    • 2014-09-05
    • 2010-12-08
    • 2018-09-05
    • 1970-01-01
    相关资源
    最近更新 更多