如何使用Babel进行CLI程序?

den*_*han 6 javascript node.js ecmascript-6 babeljs

我正在尝试使用Babel在节点上编写一些CLI程序.我见过问题如何在节点CLI程序中使用babel?loganfsmyth说:

理想情况下,您需要在分发包之前进行预编译.

好的,现在我正在使用:

"scripts": {
    "transpile": "babel cli.js --out-file cli.es5.js",
    "prepublish": "npm run transpile",
}
Run Code Online (Sandbox Code Playgroud)

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

#!/usr/bin/env node

import pkg from './package'

console.log(pkg.version);
Run Code Online (Sandbox Code Playgroud)

我会得到这个:

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

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

… … …
Run Code Online (Sandbox Code Playgroud)

这不起作用.当我尝试运行它时,我总是得到:

/usr/bin/env: node'use strict';: This file or directory does'nt exist
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个问题?

Tha*_*you 6

来自@DanPrince的解决方案是完全可以接受的,但还有另一种选择

cli.js

保留此文件es5

#!/usr/bin/env node
require("./run.es5.js");
Run Code Online (Sandbox Code Playgroud)

run.js

// Put the contents of your existing cli.js file here,
// but this time *without* the shebang
// ...
Run Code Online (Sandbox Code Playgroud)

将脚本更新为

"scripts": {
    "transpile": "babel run.js > run.es5.js",
    "prepublish": "npm run transpile",
}
Run Code Online (Sandbox Code Playgroud)

这里的想法是cli.js垫片不需要传送,所以你可以保持你的shebang在该文件中.

cli.js将加载run.es5.js哪个是babel-transiled版本run.js.