Thursday, November 2, 2017

Babel Commands and npm Project

First Example: Command Line Babel

How to compile (or, more correctly, transpile) ES6 code and run it without having to create project or config files.

Create src/Person.js
export class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.programmingLanguages = [];
  }
  getName() {
    return this.firstName + " " + this.lastName;
  }
}

Create source file src/PersonApp.js
import {Person} from './Person.js';
let lg = new Person('Lady', 'Gaga');
lg.programmingLanguages.push('Javascript','Java','Ruby');

console.log(lg.getName());
console.log(lg.programmingLanguages);
Compile and Run
$ babel --plugins transform-es2015-modules-commonjs src -d bin
src/PersonApp.js -> bin/PersonApp.js
src/Person.js -> bin/Person.js
$ node ./bin/PersonApp.js
Programmer Lady Gaga
Languages Javascript,Java,Ruby
$

Another Example: Command Line Babel

cube.js
export default function cube(x) {
  return x * x * x;
}

cubeApp.js
import cube from './cube.js';
console.log(cube(3));

Compile and Run
$ babel --plugins transform-es2015-modules-commonjs src -d bin
src/cube.js -> bin/cube.js
src/cubeApp.js -> bin/cubeApp.js
$ node ./bin/cubeApp.js
27
$ 

Another Example: Babel Project

$ mkdir -p FirstProject/src
cd FirstProject
$ npm init -y
Wrote to /Users/gMac/dev/src/javascript/tutorials/FirstProject/package.json:

{
  "name": "FirstProject",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}
$ npm install babel-cli --save-dev
$ npm install babel-preset-es2015 --save-dev
$ npm install babel-preset-stage-0 --save-dev
$ npm install babel-plugin-transform-decorators-legacy --save-dev
$ touch .babelrc
$ touch src/index.js
$ edit ./

.babelrc file in project root
{
  "presets": ["es2015"]
}

src/index.js file
"use strict";
var foo = "bar";
console.log("foo = \"" + foo + "\"");

Compile and run
$ babel src -d bin
src/index.js -> bin/index.js
$ node bin/index.js
foo = "bar"

Final Polish
Edit the package.json file and add the babel command so it looks like this:
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "babel": "babel src -d bin"
  },

And run now the compile using the npm script.
$ npm run babel
$ node bin/index.js
foo = "bar"