I've installed the latest version of babel. Currently 6.4.0. I create a file called myclass.js that has the following code.
class MyClass {
constructor(name) {
console.log("I am a MyClass object .. ", name);
}
}
var myclass = new MyClass('1234');
after creating my class I do the following in the command line.
$> babel ./src/myclass.js --out-file ./out/app.js
I would expect my app.js file to have es5 compiled javascript but it has the same exact code in it that the myclass.js file has. What am I missing that may be causing this?
You don't tell Babel to target ES5, you choose the necessary presets/plugins that do that for you. For example, if you use the
es2015
preset, this will compile ES6 code to ES5-compatible code. You don't specify a "target".The guide below will take you through using Babel to transform ES6 code into code that can run in an environment that supports ES <= 5.
0. A note on API changes from Babel 5
In the documentation for Babel 6:
And:
______
1. Install
babel-cli
First, as in the docs, you need to install
babel-cli
:______
2. Define presets in
.babelrc
Second, you need to use a
.babelrc
(docs) local to your files and explicitly define the presets that you want Babel to use. For example, for ES6+ features use theenv
preset.Install it:
And then declare it in your
.babelrc
:Note: if you are using Babel 7.x you may prefer to use a "project-wide configuration" (
babel.config.js
) (docs) which "applies broadly, even allowing plugins and presets to easily apply to files in node_modules or in symlinked packages".______
3. Run
babel
Now running the
babel
command as in your example should work:Alternatively, use a bundler like webpack, rollup, or browserify, with their respective babel plugin.