可以在不使用exports命令的情况下编写此类型脚本

Possible to write this typescript without using the exports command

本文关键字:情况下 脚本 类型 命令 exports      更新时间:2023-09-26

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

interface IBaConfigFactory {
    dateTimeNow: Date; 
}
export class BaConfigFactory implements IBaConfigFactory {
    dateTimeNow: Date;
    constructor() { 
        this.dateTimeNow = new Date();
    }
}
angular
    .module("blogApp")
    .service("BaConfigFactory", BaConfigFactory);

但是brower抱怨道:

baConfigService.ts:6未捕获引用错误:未定义导出(匿名函数)@baConfigService:ts:6 app.ts:48

根据我所学到的,我需要像Webpack或CommonJS这样的东西来让浏览器了解导出。有没有可能重写它,这样我就不会收到导出命令?专注于一次学习一件事。

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

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

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

(sample.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 = {}));

(操场上的代码)

您会注意到,在编译后的js中没有export
然后你简单地:

<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>
相关文章: