Use Babel and broserify to create your ES6 project

Source: Internet
Author: User

Original address: Setting up an ES6 Project Using Babel and Browserify

JavaScript is developing rapidly, ES6 will soon take over JS. Many well-known frameworks like Angularjs 2, React native have started to support ES6. It's time for us to embrace change, so we should start using ES6 code before almost all browsers support it.

This article will show you how to use Babel and browerify to create a project and write modern code that runs on an older version of the browser. Babel compiles the ES6 code into ES5 code that is supported by most browsers, including IE9. Browserify allows us to write code that follows the COMMONJS specification and then wraps it in the browser.

Create a Package.json file

First, let's look at the file structure of the demo we're going to create.

Under the project root directory, there are two files: Gruntfile.js and Package.json, two folders dist and modules. The Modules folder includes all modules written with ES6, and the Dist folder contains the compiled and packaged ES5 files. I did not include the. gitignore file in the folder because it is nothing but a tool file.

Now let's create the Package.json file, a standard Package.json contains many fields, such as description, version, author, and other divine horses, but in this project we only write some of the more important ones.

Package.json content is as follows:

{    "name": "Browserify-babel-demo",    "main": "Dist/module.js",    " Devdependencies ": {        " grunt ":" ^0.4.5 ",        " babelify ":" ^6.1.0 ",        " Grunt-browserify ":" ^3.8.0 ",        " Grunt-contrib-watch ":" ^0.6.1 "    }}

As you can see from the above file, the items used are:

    • Grunt JavaScript Task Building Tool
    • Grunt-browserify Grunt Browserify Mission
    • Babelify Browserify Babel Converter
    • Grunt-contrib-watch listens for every change in JavaScript and then performs the task selectively, and in our case, every time the file changes, the Browserify task is executed.

The modules in the devdependencies are only used in the development environment, not during code execution. The version number of the module can be set according to usage.

Now run the NPM install under the project root to mount the dependent modules declared in Package.json, and if you are not familiar with NPM, it is recommended that you read this article.

(Translator Note: To use the latest version of the dependency module, you can do this without prior written in the Package.json file, the following command to install: NPM Install grunt--save-dev, after the installation of the dependent module will automatically appear in the Package.json).

Create Gruntfile.js

This article assumes that you already know grunt and know how Gruntfile.js works with grunt. If you are unfamiliar, I suggest that you look at this article before reading the following.

JavaScript files written using ES6 can use JS or es6 as the extension, here for brevity, unified use of JS as the extension, Gruntfile.js code as follows:

Module.exports =function(Grunt) {grunt.initconfig {browserify: {dist: {options: {transform: [ ["Babelify", {loose:"All"}]]}, files: {//if the source file has a extension of ES6 then               //We change the name of the source file accordingly.               //The result file ' s extension is always. js"./dist/module.js": ["./modules/index.js"]}}, watch: {scripts: {files: ["./modules/*.js"], tasks: ["Browserify"]         }      }   }); Grunt.loadnpmtasks ("Grunt-browserify"); Grunt.loadnpmtasks ("Grunt-contrib-watch"); Grunt.registertask ("Default", ["Watch"]); Grunt.registertask ("Build", ["Browserify"]);};

We have defined two grunt tasks:

    1. Grunt Default/grunt: When we run this command at the root of the project, this task will listen to the changes of all JS files in the Modules folder. Grunt performs browserify tasks when any changes are detected. The watch task runs until the end of the task. CTRL + C to end the task.
    2. Grunt Build:browserify The task runs once and stops.

Each execution of the browserify task packages all ES6 code under the modules file into a single JavaScript file and then converts the ES6 code into ES5 code through babelify.

See from the above code, we give Babelify's setting is loose: "All", because we want to convert the ES5 code and we write the ES6 code can be close enough, not strictly according to the specification, so that for ES6 beginners easier to debug. See here for all the options provided by Babel.

Write Point ES6 Code

This demo uses only a bit of ES6 features, such as import and export. If you want to learn more about ES6, take a look at these articles on SitePoint. You will learn about the novel and exciting features that ES6 offers.

In our demo we will create two files under the Modules folder, Index.js and Import.js, the previous file is the main file of the project, and the latter file provides all the functions and variables as a module. That is, Index.js will import all the functions and variables from the Import.js (import).

The Import.js file is as follows:

 var  sum = (A, b = 6) = (a + b);  var  square = (b) => { return  b * b;};  var  variable = 8;class MyClass {constructor ( Credentials) { this . Name = CREDENTIALS.N        Ame  this . Enrollmentno = return  this  .name; }}export {sum, square, variable, MyClass};  

As a module, Import.js provides a variable, a class, and a function expression (the arrow function is written). The functions and variables defined in the module are not visible to the outside, unless they are explicitly exported (export). You can use the Export keyword. In the last line of import.js, we are everywhere in sum, square, variable, MyClass.

In the Index.js file, we import all the functions and variables in import.js using the Import keyword, and index.js becomes the main file for the project. From the contents of the Index.js file below you can see how we used the imported square function and the MyClass. We can import any variable and method from any number of files.

Import {sum, square, variable, MyClass} from './import '; // Console.log (Square (5)); var cred = {    ' Ritesh Kumar ',    11115078}varNew MyClass (cred); // Ritesh Kumarconsole.log (X.getname ());

If we want to import a module with a es6 extension, we must write the full file name in import. Look at the following example:

// if file extension of the importing file is. js // both below mentioned methodswork import {sum, square, variable, MyClass} from './import ' // if file extension of the importing file is. ES6 // Its mandatory to add the extensionimport {sum, square, variable, MyClass} from './import.es6 ';

If we are using browserify, we can still use the require () method to import modules that conform to the COMMONJS specification. For example: We want to use the import jquery as a module, so you can:

var $ = require (' path/to/jquery '); $ (window). Click (function() {    // Do something});

Babel can convert ES6 to ES5, but cannot package modules. Browserify debut!

ES6 's import, export combined require method allows us to freely organize our client code with modules, while writing our code using new versions of JavaScript.

As long as we run the grunt command at the terminal, it will:

    • Browserify to package all the files into a JavaScript file
    • The packaged file is converted into ES5 code by babelify
    • Generate a file named Module.js that can be run on all current browsers, including IE9

So what does module.js look like, see:

(functionE (t,n,r) {functionS (o,u) {if(!n[o]) {if(!t[o]) {varA=typeofrequire== "function" &&require;if(!u&&a)returnA (o,!0);if(i)returnI (o,!0);varf=NewError ("Cannot find module '" +o+ "'");ThrowF.code= "Module_not_found", F}varL=n[o]={exports:{}};t[o][0].call (L.exports,function(e) {varN=t[o][1][e];returnS (n?n:e)},l,l.exports,e,t,n,r)}returnN[o].exports}varI=typeofrequire== "function" &&require; for(varo=0;o<r.length;o++) s (R[o]);returns}) ({1:[function(require,module,exports) {"Use Strict"; Exports.__esmodule=true;function_classcallcheck (instance, Constructor) {if(! (InstanceinstanceofConstructor)) {Throw NewTypeError ("Cannot call a class as a function"); } }varsum =functionsum (a) {varb = arguments[1] = = = undefined? 6:arguments[1]; returnA +b;};varSquare =functionSquare (b) {"Use Strict"; returnb *b;};varVariable = 8;varMyClass = (function () {    functionMyClass (credentials) {_classcallcheck ( This, MyClass);  This. Name =Credentials.name;  This. Enrollmentno =Credentials.enrollmentno; } MyClass.prototype.getName=functionGetName () {return  This. Name;    }; returnMyClass;}) (); Exports.sum=Sum;exports.square=square;exports.variable=Variable;exports. MyClass=myclass;},{}],2:[function(require,module,exports) {' Use strict ';var_import = require ('./import ')); Console.log (0, _import.square) (5));// -varcred ={name:' Ritesh Kumar ', Enrollmentno:11115078};varx =New_import. MyClass (cred); Console.log (X.getname ());},{"./import": 1}]},{},[2]);

This file can be used in your Web page just like any other normal file, and you can use other grunt tasks, such as grunt-uglify, Grunt-rev, or other tasks, if you like. After the operation is done, you can use the Module.js in the HTML page.

 in HTML--><script src= "Path/to/module.js" ></script>

Conclusion

This article describes how to use the new features of JavaScript to create projects, and I've also covered how to configure Grunt tasks using Grunt-browserify and babelify, and we've created a sample project to show how they work, How the ES6 code is converted to ES5 code.

I hope you enjoy this article and look forward to your comments. You can also come here and play with this sample project.






Use Babel and broserify to create your ES6 project

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.