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?
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.
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 .
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With