Command line babel?
Babel is a great project and a really useful npm module. I’ve use it in almost all of my webpack experiments, but recently I had a need to use it from the command line. Thankfully there is the babel-cli module. However, things weren’t as simple as some of the blog posts I found suggested.
Starting with a new project and npm the initial installation is the usual breeze.
$ npm init -y $ npm install --save-dev babel-cli
According to the blog post I should now just be able to run babel-node – erm, no.
$ babel-node babel-node: command not found
OK, so it’s Ubuntu and bash which means the PATH isn’t pointing to the correct file. That’s reasonable given I’ve just installed it, but what is the correct path? Given that npm installs things on a per project basis it’s likely something in node_modules? A quick search reveals that to be the case.
$ ls -l node_modules/.bin total 0 ... lrwxrwxrwx 1 david david 30 Apr 16 13:31 babel-node -> ../babel-cli/bin/babel-node.js ...
To avoid this being a recurring issue I adjusted the PATH to include that directory (as a relative path).
$ export PATH=$PATH:node_modules/.bin
Now I could run babel-node, but using funky modern javascript syntax failed. I needed the es2015 preset.
$ npm install --save-dev babel-preset-es2015
Once installed I needed to tell babel to use it, which was as simple as
$ babel-node --presets es2015 ...
However, what are the chances of me remembering that every time I need it? So, there must be a better way to tell babel to always use the preset. Further reading revealed 2 options – add a .babelrc file or add an entry in package.json. I chose the package.json file for no other reason than it was one less file to create/manage. The entry is pretty simple and exactly as you’d expect.
"babel": { "presets": ["es2015"] }
Now running is as simple as
$ babel-node index.js
However…
As I started writing more javascript I ran into problems when I used the new ES7 spread operator, ‘…’. It is supported by babel, but requires a plugin to be installed and used. Finding and adding the plugin was simple enough,
$ npm install --save-dev babel-plugin-transform-object-rest-spread
I thought that I could add it’s use via the package.json file, but my attempts failed, so I added a .babelrc file with the appropriate sections and all was well.
$ cat .babelrc { "presets": [ "es2015" ], "plugins": [ "transform-object-rest-spread" ] }
Hopefully this will help someone else!