【问题标题】:How to write typescript executable file?如何编写打字稿可执行文件?
【发布时间】:2021-02-04 08:12:43
【问题描述】:

使用babel-cli,您可以使用 es2015 语法轻松编写一些节点可执行文件。为此,您只需要添加适当的 shebang #!/usr/bin/env babel-node

例如,

#!/usr/bin/env babel-node

import fs from 'fs';

fs.readFileSync('./some-file.csv');

我想知道如何使用 TypeScript 来做到这一点?

更新: 尝试过ts-node - 即使对于像这样的 HelloWorld 示例也会出现尴尬的错误

const say = (word: string) => {
    console.log(word);
}

say('hello');

它不能通过ts-node test.ts 或使用#!/usr/bin/env ts-node 工作;

在这两种情况下我都得到了

SyntaxError: Unexpected token :
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at Object.<anonymous> (/usr/local/lib/node_modules/ts-node/src/bin/ts-node.ts:110:12)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)

更新使ts-node 工作。仅当文件具有 .ts 扩展名时才有效。对于没有扩展名但带有 shebang 的文件 - 它不起作用。为反映所需行为的项目创建了 github issue

【问题讨论】:

    标签: node.js typescript


    【解决方案1】:

    我相信你正在寻找ts-node

    #!/usr/bin/env ts-node
    
    ...rest of script
    

    作者确认此用法在这里有效: https://github.com/TypeStrong/ts-node/issues/73

    附言我称之为executable,而不是binary

    【讨论】:

    【解决方案2】:

    请注意,自从@ValeriiVasin 尝试的方法和@Paarth 的回答中推荐的方法以来,事情已经发生了变化。

    Support for shebangs 正式加入ts-node v8.9.0。推荐的 shebang 字符串现在包含 -script 后缀:

    #!/usr/bin/env ts-node-script
    

    使用 fs.readFileSync("somefile.json") 的脚本正在为我使用这个 shebang。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-29
      • 1970-01-01
      • 2018-09-18
      • 1970-01-01
      • 2018-08-24
      • 1970-01-01
      • 2020-01-19
      • 2018-04-16
      相关资源
      最近更新 更多