Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use Babel for CLI program?

I'm trying to write some CLI program on node using Babel. I'd seen question How do I use babel in a node CLI program? and there loganfsmyth said:

Ideally you'd precompile before distributing your package.

Okay, now I'm using:

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

But, I faced the problem, when Babel adds 'use strict'; line right behind #!/usr/bin/env node header. For example, if I have cli.js:

#!/usr/bin/env node

import pkg from './package'

console.log(pkg.version);

I'll get this:

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

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

… … …

And this doesn't work. When I try to run it, I always get:

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

How can I solved this problem?

like image 226
denysdovhan Avatar asked Oct 31 '15 12:10

denysdovhan


People also ask

What is the use of Babel CLI?

Babel comes with a built-in CLI which can be used to compile files from the command line. In addition, various entry point scripts live in the top-level package at @babel/cli/bin . There is a shell-executable utility script, babel-external-helpers.

How do I run code on Babel?

Simply add a "scripts" field to your package. json and put the babel command inside there as build . This will run Babel the same way as before and the output will be present in lib directory, only now we are using a local copy. Alternatively, you can reference the babel cli inside of node_modules .

Where can I use Babel?

Babel is a JavaScript compiler Babel is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments. Here are the main things Babel can do for you: Transform syntax.


1 Answers

The solution from @DanPrince is perfectly acceptable but there's an alternative

cli.js

keep this file 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
// ...

Update your scripts to

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

The idea here is that the cli.js shim doesn't need to be tranpsiled so you can keep your shebang in that file.

cli.js will just load run.es5.js which is the babel-transpiled version of run.js.

like image 78
Mulan Avatar answered Sep 29 '22 10:09

Mulan