Reputation: 986
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?
Upvotes: 6
Views: 1712
Reputation: 135425
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
.
Upvotes: 6
Reputation: 30009
You could use another NPM script to add the shebang as the last part of your build process. It ain't pretty 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
would 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 could 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 that you are on a system with bash (or some alternate compatible shell), however you could make it cross-platform by rewriting the build scripts to use node implementations of these commands with something like ShellJS.
Upvotes: 1