【问题标题】:How can I use Babel for CLI program?如何将 Babel 用于 CLI 程序?
【发布时间】:2015-10-31 12:50:23
【问题描述】:

我正在尝试使用 Babel 在节点上编写一些 CLI 程序。我见过How do I use babel in a node CLI program? 的问题,loganfsmyth 说:

理想情况下,您应该在分发包之前进行预编译。

好的,现在我正在使用:

"scripts": {
    "transpile": "babel cli.js --out-file cli.es5.js",
    "prepublish": "npm run transpile",
}

但是,当 Babel 在 #!/usr/bin/env node 标头后面添加 'use strict'; 行时,我遇到了问题。例如,如果我有cli.js:

#!/usr/bin/env node

import pkg from './package'

console.log(pkg.version);

我会得到这个:

#!/usr/bin/env node'use strict';

var _package = require('./package');

… … …

这行不通。当我尝试运行它时,我总是得到:

/usr/bin/env: node'use strict';: This file or directory does'nt exist

我该如何解决这个问题?

【问题讨论】:

  • 你真的需要 Babel吗? Node 支持 V8 中包含的任何 ES6 特性:nodejs.org/en/docs/es6
  • 这个程序应该在节点上运行>=0.10,所以我需要。

标签: javascript node.js ecmascript-6 babeljs


【解决方案1】:

@DanPrince 的解决方案完全可以接受,但还有其他选择

cli.js

保留这个文件 es5

#!/usr/bin/env node
require("./run.es5.js");

run.js

// Put the contents of your existing cli.js file here,
// but this time *without* the shebang
// ...

将您的脚本更新为

"scripts": {
    "transpile": "babel run.js > run.es5.js",
    "prepublish": "npm run transpile",
}

这里的想法是 cli.js shim 不需要被转换,因此您可以将 shebang 保存在该文件中。

cli.js 只会加载 run.es5.js,这是 run.js 的 babel 转译版本。

【讨论】:

  • 谢谢!这就是我要找的。它似乎比 bash 脚本更优雅。
【解决方案2】:

您可以使用另一个 NPM 脚本将 shebang 添加为构建过程的最后一部分。它不漂亮,但它有效。

"scripts": {
  "transpile": "babel cli.js --out-file es5.js",
  "shebang": "echo -e '#!/usr/bin/env/node\n' $(cat es5.js) > cli.es5.js",
  "prepublish": "npm run transpile && npm run shebang",
}

那么你原来的cli.js就会变成

import pkg from './package'

console.log(pkg.version);

生成的es5.js 文件变为

'use strict';

var _package = require('./package');

最后,cli.es5.js 变成了

#!/usr/bin/env node
'use strict';

var _package = require('./package');

这可以通过一个干净的脚本来改进。

"scripts": {
  "transpile": "babel cli.js --out-file es5.js",
  "shebang": "echo -e '#!/usr/bin/env/node\n' $(cat es5.js) > cli.es5.js",
  "clean": "rm es5.js cli.es5.js",
  "prepublish": "npm run clean && npm run transpile && npm run shebang",
}

当然,这要求你在一个带有 bash(或其他兼容的 shell)的系统上,但是你可以通过重写构建脚本来使用这些命令的节点实现,比如 ShellJS .

【讨论】:

  • 它看起来不是一个优雅的解决方案,但是,是的,应该可以。非常感谢!
猜你喜欢
  • 2015-10-05
  • 1970-01-01
  • 2017-08-06
  • 2018-10-26
  • 2020-05-28
  • 2019-07-17
  • 2018-12-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多