【问题标题】:TypeScript compile-time constants?TypeScript 编译时常量?
【发布时间】:2017-06-16 23:12:25
【问题描述】:

我正在用 TypeScript 编写一个库,我想同时针对 Node 和 Browser。现在我用两个不同的目标运行tsc 两次。那部分工作正常。

但是,我的代码的一小部分是特定于目标的。我需要能够执行以下操作:

if(BUILD_TARGET === 'node') {
    // do something
} else {
    // do something else
}

有什么方法可以在编译时注入这些常量,以便它们可以被 tsc 本身优化掉,或者通过 UglifyJS(或一些这样的工具)?

【问题讨论】:

  • 您可以检查window 对象的存在,该对象将存在于浏览器中但不在节点中
  • @NitzanTomer 这可能会解决一些场景,但我仍然想要一些可以预编译的东西。

标签: typescript


【解决方案1】:

打字稿中最接近编译时常量的是const enums - 根据documentation,“常量枚举成员在使用站点内联”。 Typescript 不会删除死代码,之后您必须使用其他工具来删除 if (0 === 1) 分支。

您将需要两个不同的tsconfig.json 文件,每个文件都将包含一个对同一枚举类型具有不同定义的文件。

tsconfig.browser.json

{
  "files": [
    "t.ts",
    "target-enum-browser.d.ts"
  ]
}

target-enum-browser.d.ts

declare module 'target-enum' {
    export const enum Target { Node, Browser, Current = Browser }
}

tsconfig.node.json

{
  "files": [
    "t.ts",
    "target-enum-node.d.ts"
  ]
}

target-enum-node.d.ts

declare module 'target-enum' {
    export const enum Target { Node, Browser, Current = Node }
}

t.ts

import {Target} from 'target-enum';

if (Target.Current === Target.Browser) {
    console.log('browser');

} else if (Target.Current === Target.Node) {
    console.log('node');

} else {
    console.log('?');
}

tsc --project tsconfig.browser.json编译

"use strict";
exports.__esModule = true;
if (1 /* Current */ === 1 /* Browser */) {
    console.log('browser');
}
else if (1 /* Current */ === 0 /* Node */) {
    console.log('node');
}
else {
    console.log('?');
}

tsc --project tsconfig.node.json编译

"use strict";
exports.__esModule = true;
if (0 /* Current */ === 1 /* Browser */) {
    console.log('browser');
}
else if (0 /* Current */ === 0 /* Node */) {
    console.log('node');
}
else {
    console.log('?');
}

【讨论】:

    【解决方案2】:

    https://github.com/Morglod/tsts

    目前正在研究编译时转换器

    const numbers = [ 1, 2, 3, 4, 5, 6, 7, 8 ];
    const result = comptime(() => {
        return numbers.reduce((total, x) => sum(total, x), 0);
    });
    

    const result = (() => { return (36); })();
    

    【讨论】:

      猜你喜欢
      • 2011-11-25
      • 2011-12-26
      • 1970-01-01
      • 2012-02-23
      • 2014-09-03
      • 2012-06-13
      • 1970-01-01
      相关资源
      最近更新 更多