So, our javascript is just your run-of-the-mill, runs in the browser, ES5, boring old javascript. But we're making a shiny new, state-of-the-art javascript application, so we should really be pushing the latest and greatest ES6 syntax. Step up Babel.
Babel is a javascript transpiler. It will transpile (convert from one format to another), ES6 syntax javascript, to
ES5 syntax javascript that is runnable in the browser. For this, we will require
broccoli-babel-transpiler.
1 | yarn add --dev @babel/core@^7.1.0 broccoli-babel-transpiler@^7.0.0 @babel/preset-env@^7.1.0 |
Now open app/app.js and set the contents to:
1 | // app/app.js |
And Brocfile.js
1 | // Brocfile.js |
Make a .babelrc file in the root directory:
1
2
3
4
5
6
7
8
9
10
11
12{
"presets": [
[
"@babel/env",
{
"targets": {
"browsers": ["last 2 versions"]
}
}
]
]
}
So what's happening here? First off, we've declared js as a mutable variable (let) rather than an immutable
variable (const) so we can re-assign it. Next, we pass the js tree into the babel transpiler, this will
transpile the ES6 syntax to ES5. The .bablerc is the standard practice for configuring Babel, here we're targeting
the last 2 major versions of each browser for transpilation, this means that language features that are unsupported in
these browsers will have them transpiled into a format that is compatible.
If you build this now, and open dist/assets/app.js, you should see:
1 | // dist/assets/app.js |
So, a few things have happened here:
consthas been changed tovar- The arrow function
() => {}inside the setTimeout has been converted to a regular function. - The use of
thiswithin the arrow function refers to the correctthiscontext. - You should also notice the sourcemap at the bottom, this has to be
inlinefor this plugin to work
If you run this in the browser, you'll see the message and the correct this is logged to the console.
Now try adding a debugger; statement into the function and notice that the console stops at the breakpoint.
The presented source code should be the original ES6 version, not the transpiled ES5 version.
Completed Branch: 05-es6-transpilation
Next: 06-es6-modules