Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compile a file with babel CLI [duplicate]

I'm trying to compile a simple es6 file with babel CLI

Given the details below: what's going wrong?

$ node --version
v5.0.0

$ npm --version
3.3.6

$ npm init
$ npm install --save-dev babel-cli

$ echo -e 'import url from "url"\nconsole.log(`2+2=${2+2}`)' > script.js

$ ./node_modules/.bin/babel  script.js 
import url from "url";
console.log(`2+2=${ 2 + 2 }`);

In other words: I put in ES6 and I get out ES6 (albeit with slightly different spacing, and semicolons added). I'm expecting to see imports converted to requires, and to see my back-ticks disappear.

That is: I want ES5 out.

What do I need to do differently?

like image 526
Bosh Avatar asked Nov 11 '15 23:11

Bosh


People also ask

How do you compile with babel?

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 .

What is babel CLI?

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.

Can the npm view babel CLI versions command will display all the versions of babel?

You can also check the version of babel-cli by finding the babel-cli folder in node_modules and looking at the version property of the package. json that is at the base of that folder. If babel-cli was installed globally via -g flag of npm install , you could check the version by executing command babel --version .


2 Answers

Babel version 6 ships "without any default transforms". You can read more about the changes in this blog post

To transpile es6 to es5 you will need to do the following:

  1. run npm i --save-dev babel-preset-es2015

  2. Create a .babelrc file in the root of your project with the following:

    {

       "presets": ["es2015"]
    

    }

There's a lot of configuration you can do on top of that, but that should atleast get you started.

like image 157
undefined Avatar answered Nov 01 '22 01:11

undefined


The trick: need to pass --presets "es2015" as an argument to babel.

As in:

$ ./node_modules/.bin/babel  --presets "es2015" script.js 
"use strict";

var _url = require("url");

var _url2 = _interopRequireDefault(_url);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

console.log("2+2=" + (2 + 2));
like image 43
Bosh Avatar answered Nov 01 '22 02:11

Bosh