How can I use the Babel program for the CLI?

I am trying to write some CLI program on node using Babel. I saw a question How to use babel in a CLI node program? and there loganfsmyth said:

Ideally, you should precompile before distributing your package.

Ok, now I use:

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

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

 #!/usr/bin/env node import pkg from './package' console.log(pkg.version); 

I will get this:

 #!/usr/bin/env node'use strict'; var _package = require('./package'); … … … 

And that will not 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 solve this problem?

+5
source share
2 answers

The solution from @DanPrince is quite acceptable, but there is an alternative

cli.js

save this es5 file

 #!/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 spacer cli.js not need transcryption so you can save your shebang in this file.

cli.js will just load run.es5.js , which is the version of run.js passed in using babel.

+6
source

You can use another NPM script to add shebang as the last part of your build process. This is not very, but it works.

 "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", } 

Then your original cli.js will become

 import pkg from './package' console.log(pkg.version); 

The resulting es5.js file becomes

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

And finally, cli.es5.js becomes

 #!/usr/bin/env node 'use strict'; var _package = require('./package'); 

This can be improved with a clean script.

 "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", } 

Of course, this requires you to be on a system with bash (or some alternative compatible shell), however you could make it cross-platform by rewriting build scripts to use node implementations of these commands with something like ShellJS .

+1
source

Source: https://habr.com/ru/post/1234914/


All Articles