First, Babel is a widely used JavaScript compiler that converts ECMAScript 2015+ (ES6 and higher) code into backwards-compatible JavaScript versions, enabling it to run in current and older browsers or environments. The following are the steps to install Babel locally and use ES6 in the browser:
Step 1: Install Node.js and npm
Babel requires a Node.js environment and npm (Node Package Manager). If not installed, visit Node.js official website to download and install.
Step 2: Initialize a New Project
Create a new directory on your computer to store project files. Navigate to this directory via the command line and execute the following command to initialize the project:
bashnpm init -y
This will create a package.json file for managing project dependencies.
Step 3: Install Babel
In the project directory, execute the following command to install Babel and its necessary plugins:
bashnpm install --save-dev @babel/core @babel/cli @babel/preset-env
Step 4: Configure Babel
Create a .babelrc configuration file for Babel in the project root directory with the following content:
json{ "presets": ["@babel/preset-env"] }
This tells Babel to use @babel/preset-env, which is an intelligent preset that allows you to use the latest JavaScript without manually managing the syntax transformations required for the target environment (polyfills excluded).
Step 5: Create an Example ES6 Script
Create a folder named src in the project and within it, create a file named app.js. Write some ES6 code, for example, using arrow functions:
javascriptconst greet = (name) => { return `Hello, ${name}!`; } console.log(greet('World'));
Step 6: Use Babel to Compile ES6 Code
Run the following command in the terminal to compile ES6 code into ES5:
bashnpx babel src --out-dir lib
This will compile all JavaScript files in the src directory into ES5 and output them to the lib directory.
Step 7: Use the Compiled Code in the Browser
Create an HTML file index.html and reference the compiled JavaScript file within it:
html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>ES6 Test</title> </head> <body> <script src="lib/app.js"></script> </body> </html>
Open this HTML file in the browser, and you should see "Hello, World!" output in the console.
By following these steps, you can use Babel locally to transpile JavaScript code from ES6 and higher into a version that browsers can execute, ensuring cross-browser compatibility.