5

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?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Bosh
  • 8,138
  • 11
  • 51
  • 77
  • What version of Babel? They very recently [completely changed](https://babeljs.io/blog/2015/10/29/6.0.0/) how things work – Kyeotic Nov 11 '15 at 23:43
  • For the record, 6.1 (Another way to say it: the commands shown above were run at the time of my question.) – Bosh Nov 12 '15 at 01:29
  • This question is asked multiple times per day. Please use the search or at least browse the `babeljs` tag (I also suggest to read the *tag descriptions* of the tags you add) – Felix Kling Nov 12 '15 at 17:43

2 Answers2

10

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.

undefined
  • 2,154
  • 15
  • 16
1

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));
Bosh
  • 8,138
  • 11
  • 51
  • 77