2

学习 TypeScript 并拥有一个简单的 Angular 服务:

interface IBaConfigFactory {
    dateTimeNow: Date; 
}

export class BaConfigFactory implements IBaConfigFactory {
    dateTimeNow: Date;

    constructor() { 
        this.dateTimeNow = new Date();
    }
}

angular
    .module("blogApp")
    .service("BaConfigFactory", BaConfigFactory);

但是浏览器抱怨:

baConfigService.ts:6 未捕获的 ReferenceError:未定义导出(匿名函数)@ baConfigService.ts:6 app.ts:48

根据我正在学习的内容,我需要 Webpack 或 CommonJS 之类的东西来让浏览器理解导出。是否可以重写它以便我不使用导出命令?专注于一次学习一件事。

4

1 回答 1

1

如果您不使用模块系统加载文件,并且不将代码放在模块/命名空间中,则不需要导出。

例如,这应该可以正常工作:

class MyClass {
    private x: number;

    constructor(x: number) {
        this.x = x;
    }

    getX(): number {
        return this.x;
    }

    doit(y: number): number {
        return this.x * y;
    }
}

function echo(value: any): any {
    return value;
}

(样本.ts)

<html>
    <head>
        <script src="example.js"></script>
        <script>
            var a1 = new MyClass(10),
                a2 = new MyClass(43);

            console.log(echo("hey there!"));
            console.log(a1.doit(a2.getX()));
        </script>
    </head>
    <body></body>
</html>

但是,使用export应该没问题,因为它不应该出现在编译的 js 中(只要确保不要使用-m--module编译器选项中)。

例如,这个:

module MyModule {
    export class MyClass {
        private x: number;

        constructor(x: number) {
            this.x = x;
        }

        getX(): number {
            return this.x;
        }

        doit(y: number): number {
            return this.x * y;
        }
    }

    export function echo(value: any): any {
        return value;
    }
}

编译成这样:

var MyModule;
(function (MyModule) {
    var MyClass = (function () {
        function MyClass(x) {
            this.x = x;
        }
        MyClass.prototype.getX = function () {
            return this.x;
        };
        MyClass.prototype.doit = function (y) {
            return this.x * y;
        };
        return MyClass;
    }());
    MyModule.MyClass = MyClass;
    function echo(value) {
        return value;
    }
    MyModule.echo = echo;
})(MyModule || (MyModule = {}));

操场上的代码

而且你会注意到export编译的js中没有。
然后你只需:

<html>
    <head>
        <script src="example.js"></script>
        <script>
            var a1 = new MyModule.MyClass(10),
                a2 = new MyModule.MyClass(43);

            console.log(MyModule.echo("hey there!"));
            console.log(a1.doit(a2.getX()));
        </script>
    </head>
    <body></body>
</html>
于 2016-04-19T20:05:06.247 回答