简体   繁体   English

TypeType类以严格模式导出为UMD模块

[英]TypeScript Class exported as a UMD module with strict mode

Is there a way I can have a TypeScript class exported as a UMD module with strict mode enabled? 有没有一种方法可以将TypeScript类导出为启用了严格模式的UMD模块? The "gotcha" is the strict mode part. “陷阱”是严格模式部分。

My code looks something like: 我的代码如下所示:

class Foo {
    bar(): Foo.Bam {}
}

namespace Foo {
    export function boom() {}
    export interface Bam {}
}

export = Foo;

Elsewhere the module can be used like: 可以在其他地方使用该模块,例如:

import * as Foo from 'my-module';

var foo = new Foo();
foo.bar()

Foo.boom();

interface Kaboom extends Foo.Bam {}

I want strict mode to apply to all of Foo , but not to the entire script, as it may be concat with other unknown scripts. 我希望严格模式适用于所有Foo ,而不适用于整个脚本,因为它可能与其他未知脚本并存。

A definition file is also being generated. 还正在生成定义文件。

I can just wrap everything in a closure during the build process, but I'm looking for a pre-compilation solution first. 我可以在构建过程中将所有内容包装在一个封闭的容器中,但是我首先要寻找一个预编译解决方案。

Edit: 编辑:

Added more details to my question, just in case someone finds a way in the future. 为我的问题添加了更多详细信息,以防万一将来有人找到方法。

I ended up just adding a simple post-compile fix. 我最终只是添加了一个简单的编译后修复程序。 After the UMD module is generated. UMD模块生成后。 I replace this line: 我替换此行:

})(["require", "exports"], function (require, exports) {

With this line: 用这行:

})(["require", "exports"], function (require, exports) {"use strict";

Now everything inside the module is strict, and the script itself is not. 现在,模块中的所有内容都是严格的,脚本本身不是严格的。

If you are using your modules in the standard way (ie loading them as you need them) you can add it to the top of your file - the statement will be scoped to the file. 如果您以标准方式使用模块(即,根据需要加载模块),则可以将其添加到文件的顶部-该语句将作用于文件。

"use strict"

class Foo {
    bar() {}
}

namespace Foo {
    export function bar() {}
}

export = Foo;

If you are actually combining your output into a single file, you can't limit the scope of the statement without introducing namespaces (aside: I'm not a fan of internal modules / namespaces). 如果您实际上是将输出合并到一个文件中,则在不引入名称空间的情况下就不能限制语句的范围(除了:我不是内部模块/名称空间的粉丝)。

namespace Example {
    "use strict"

    export class Foo {
        bar() {}
    }
}

namespace Foo {
    export function bar() {}
}

export = Example.Foo;

It's a fixed issue. 这是一个固定的问题。 See Change prologue emit location to inside module IIFEs . 请参阅将序言发出位置更改为模块IIFE内部

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM