Last active
June 19, 2021 08:01
-
-
Save ShuvoHabib/249caa0e13781610f1c5903318759f21 to your computer and use it in GitHub Desktop.
ES6 on the fly : Babelify your ES6 to ES5 for browser support
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Currently all browsers don’t support all the new ECMAScript 2015 features yet. You need to use a compiler (transpiler) to transform your ECMAScript 6 code to ECMAScript 5 compatible code.Babel has become the de-facto standard to compile ECMAScript 6 applications to a version of ECMAScript that can run in current browsers. Let dive into Babel, assuming you've npm pre-installed... | |
//First Navigate(cd) to the directory by command prompt you're going to work | |
//Type the following command below to create a package.json file: | |
//npm init | |
//The following command is to install the babel-cli and babel-core modules: | |
//npm install babel-cli babel-core --save-dev | |
//The following command is to install the ECMAScript 2015 preset: | |
//npm install babel-preset-es2015 --save-dev | |
//Install http-server in your project. http-server is a lightweight web server we use to run the application locally during development. | |
//npm install http-server --save-dev | |
//Open package.json in your favorite code editor. In the scripts section, remove the test script, and add two new scripts: a script named babel that compiles main.js to a version of ECMAScript that can run in current browsers, and a script named start that starts the local web server. The scripts section should now look like this: | |
"scripts": { | |
"build": "babel --presets es2015 js/main.js -o build/main.bundle.js", | |
"start": "http-server" | |
}, | |
//Add a file naming .babelrc. Write the presets as given below. | |
{ | |
"presets": ["es2015"] | |
} | |
//Write your JS code on a file 'main.js'. keep that file in a folder naming 'js'. Your compiled js file will be in a build folder naming 'main.bundle.js' the compiled version of js/main.js. | |
//Open index.html in your code editor, and add the tag as follows to load build/main.bundle.js | |
<script src="build/main.bundle.js"></script> | |
//For compiling ES6 code run the command | |
//npm run build | |
//Open a new command prompt. Navigate (cd) to the directory, and type the following command to start http-server: | |
//npm start | |
//Open a browser and access http://localhost:8080 | |
//If port 8080 is already in use on your computer, modify the start script in package.json and specify a port that is available on your computer. For example: | |
"scripts": { | |
"build": "babel --presets es2015 js/main.js -o build/main.bundle.js", | |
"start": "http-server -p 9000" | |
}, |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment