如何使用 Babel 作为 CLI 程序?

How can I use Babel for CLI program?

我正在尝试使用 Babel 在节点上编写一些 CLI 程序。我看到问题 and there loganfsmyth 说:

Ideally you'd precompile before distributing your package.

好的,现在我正在使用:

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

但是,当 Babel 在 #!/usr/bin/env node header 后面添加 '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

我该如何解决这个问题?

您可以使用另一个 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)的系统,但是您可以通过重写构建脚本以使用 node 使其跨平台这些命令的实现类似于 ShellJS

@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 转译版本