Babel is an excellent entry in the Web Developer toolset. This is an amazing tool that has been around for a while, but now almost every JavaScript developer relies on it, and this situation will continue, because Babel is now indispensable and has solved everyone's big problems.
- Introduction to Tongtian Tower
- Install Babel
- Babel configuration example
- Babel presets
- Use Babel with Webpack
This article introduces Babel 7 (the current stable release)
Introduction to Tongtian Tower
Babel is an amazing tool that has been around for a while, but now it’s almostJavaScriptDevelopers rely on it, and this situation will continue, because Babel is now indispensable and has solved everyone's big problems.
Which problem?
A problem that every web developer will definitely encounter: JavaScript functionality is available in the latest version of the browser, but not in the earlier version. Maybe Chrome or Firefox can achieve it, but Safari iOS and Edge cannot.
For example, ES6 introducedArrow function:
[1, 2, 3].map((n) => n + 1)
All modern browsers now support this feature. IE11 does not support it, nor does Opera Mini (how do I know? CheckedES6 compatibility table).
So how should you deal with this problem? Should you move on and let customers who use older/incompatible browsers stay, or should you write older JavaScript code to satisfy all users?
Enter Babel. Tongtian Tower istranslater: Accept code written in one standard and convert it to code written in another standard.
You can configure Babel to convert modern ES2017 JavaScript to JavaScript ES5 syntax:
[1, 2, 3].map(function(n) {
return n + 1
})
This must happen at build time, so you must set up a workflow that can handle it for you.WebpackIs a common solution.
(PS, if all thisESSounds confusing you, see more information about ES versionIn the ECMAScript guide)
Install Babel
Babel is easy to install and usenpm, Located locally in the project:
npm install --save-dev @babel/core @babel/cli
In the past I suggested to install
babel-cli
Globally, but Babel maintainers do not recommend this now, because using it locally can use different versions of Babel in each project, and checking in babel in the repository is more suitable for team work
Since npm now comes withnpx
, You can run the locally installed CLI package by typing the following command in the project folder:
So we can run by running Babel
npx babel script.js
Babel configuration example
Babel doesn't do anything useful out of the box, you need to configure it and add plugins.
To solve the problem we discussed in the introduction (using the arrow function in each browser), we can run
npm install --save-dev \
@babel/plugin-transform-arrow-functions
Download the package tonode_modules
Application folder, then we need to add
{
"plugins": ["@babel/plugin-transform-arrow-functions"]
}
To.babelrc
The file exists in the root folder of the application. If you don’t have the file yet, just create a blank file and put its contents in it.
Tip: If you have never seen a dot file (files that start with a dot), it may seem strange at first, because the file may not appear in the file manager because it is a hidden file.
Now if we have ascript.js
Files containing the following content:
var a = () => {};
var a = (b) => b;
const double = [1,2,3].map((num) => num * 2);
console.log(double); // [2,4,6]
var bob = {
_name: “Bob”,
_friends: [“Sally”, “Tom”],
printFriends() {
this._friends.forEach(f =>
console.log(this._name + " knows " + f));
}
};
console.log(bob.printFriends());
Runbabel script.js
The following code will be output:
var a = function () {};var a = function (b) {
return b;
};
const double = [1, 2, 3].map(function (num) {
return num * 2;
});console.log(double); // [2,4,6]
var bob = {
_name: “Bob”,
_friends: [“Sally”, “Tom”],
printFriends() {
var _this = this;
<span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">_friends</span>.<span style="color:#a6e22e">forEach</span>(<span style="color:#66d9ef">function</span> (<span style="color:#a6e22e">f</span>) {
<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">_this</span>.<span style="color:#a6e22e">_name</span> <span style="color:#f92672">+</span> <span style="color:#e6db74">" knows "</span> <span style="color:#f92672">+</span> <span style="color:#a6e22e">f</span>);
});
}
};
console.log(bob.printFriends());
As you can see, the arrow functions have all been converted to JavaScript ES5 functions.
Babel presets
We just saw how to configure Babel to transform specific JavaScript functions in the previous article.
You can add more plug-ins, but you can't add them to the configuration function one by one, which is impractical.
This is why Babel providesPreset.
The most popular preset isenv
withreact
.
Tip: Babel 7 has deprecated (and deleted) annual presets, such as
preset-es2017
And stage presets. use@babel/preset-env
instead.
env
Preset
Thisenv
The preset is very good: you tell it to support the environment, it can do all the work for you,Supports all modern JavaScript functions.
For example, "supports the last 2 versions of each browser, but for Safari, we support all versions after Safari 7.
{
"presets": [
["env", {
"targets": {
"browsers": ["last 2 versions", "safari >= 7"]
}
}]
]
}
Or "I don’t need browser support, just let me use it togetherNode.js6.10"
{
"presets": [
["env", {
"targets": {
"node": "6.10"
}
}]
]
}
react
Preset
Thisreact
When writing React applications, presets are very convenient: addpreset-flow
,syntax-jsx
,transform-react-jsx
,transform-react-display-name
.
By including it, you are ready to develop React applications using JSX transformation and Flow support.
More information about presets
https://babeljs.io/docs/plugins/
Use Babel with Webpack
If you want to run modern JavaScript in your browser, Babel alone is not enough, you also need to bundle the code. Webpack is the perfect tool for this purpose.
Tip: please readWebpack guideIf you are not familiar with webpack
Modern JS requires two different phases: the compilation phase and the runtime phase. This is because certain ES6+ features require polyfills or runtime helpers.
To install the Babel polyfill runtime features, run
npm install @babel/polyfill \
@babel/runtime \
@babel/plugin-transform-runtime
Now in yourswebpack.config.js
File addition:
entry: [
'babel-polyfill',
// your app scripts should be here
],
module: {
loaders: [
// Babel loader compiles ES2015 into ES5 for
// complete cross-browser support
{
loader: ‘babel-loader’,
test: /.js$/,
// only include files present in the src
subdirectory
include: [path.resolve(__dirname, “src”)],
// exclude node_modules, equivalent to the above line
exclude: /node_modules/,
query: {
// Use the default ES2015 preset
// to include all ES2015 features
presets: [‘es2015’],
plugins: [‘transform-runtime’]
}
}
]
}
By keeping the preset and plugin information inwebpack.config.js
Files we can avoid.babelrc
file.
More devtools tutorials:
- Yoman Introduction
- Bower, browser package manager
- Introduction to front-end testing
- Use node-webkit to create desktop applications
- VS Code: Use language-specific settings
- Introduction to Webpack
- A short and concise guide to the Tower of Babel
- Yarn introduction
- Overview of Browser DevTools
- Use Prettier to format code
- Use ESLint to keep your code clean
- List of cool Chrome DevTools tips and tricks
- Test JavaScript with Jest
- How to use Visual Studio Code
- Introduction to Electronics
- Package, simpler Webpack
- Emmet's HTML reference
- V8 JavaScript engine
- Configure VS Code
- Configure macOS command line
- How to disable ESLint rules
- How to open VS Code from the command line
- How to set up hot reinstallation on Electron