English 中文(简体)
Transpile ES6 Modules to ES5
  • 时间:2024-12-22

BabelJS - Transpile ES6 Modules to ES5


Previous Page Next Page  

In this chapter, we will see how to transpile ES6 modules to ES5 using Babel.

Modules

Consider a scenario where parts of JavaScript code need to be reused. ES6 comes to your rescue with the concept of Modules.

A module is nothing more than a chunk of JavaScript code written in a file. The functions or variables in a module are not available for use, unless the module file exports them.

In simpler terms, the modules help you to write the code in your module and expose only those parts of the code that should be accessed by other parts of your code.

Let us consider an example to understand how to use module and how to export it to make use of it in the code.

Example

add.js

var add = (x,y) => {
   return x+y;
}

module.exports=add;

multiply.js

var multiply = (x,y) => {
   return x*y;
};

module.exports = multiply;

main.js

import add from  ./add ;
import multiply from  ./multiply 

let a = add(10,20);
let b = multiply(40,10);

console.log("%c"+a,"font-size:30px;color:green;");
console.log("%c"+b,"font-size:30px;color:green;");

I have three files add.js that adds 2 given numbers, multiply.js that multippes two given numbers and main.js, which calls add and multiply, and consoles the output.

To give add.js and multiply.js in main.js, we have to export it first as shown below −

module.exports = add;
module.exports = multiply;

To use them in main.js, we need to import them as shown below

import add from  ./add ;
import multiply from  ./multiply 

We need module bundler to build the files, so that we can execute them in the browser.

We can do that −

    Using Webpack

    Using Gulp

ES6 modules and Webpack

In this section, we will see what the ES6 modules are. We will also learn how to use webpack.

Before we start, we need to install the following packages −

npm install --save-dev webpack
npm install --save-dev webpack-dev-server
npm install --save-dev babel-core
npm install --save-dev babel-loader
npm install --save-dev babel-preset-env

Package.json

ES6 modules Webpack

We have added pack and pubpsh tasks to scripts to run them using npm. Here is the webpack.config.js file which will build the final file.

webpack.config.js

var path = require( path );

module.exports = {
   entry: {
      app:  ./src/main.js 
   },
   output: {
      path: path.resolve(__dirname,  dev ),
      filename:  main_bundle.js 
   },
   mode: development ,
   module: {
      rules: [
         {
            test: /.js$/,
            include: path.resolve(__dirname,  src ),
            loader:  babel-loader ,
            query: {
               presets: [ env ]
            }
         }
      ]
   }
};

Run the command npm run pack to build the files. The final file will be stored in the dev/ folder.

command

npm run pack

Npm Run Pack

dev/main_bundle.js common file is created. This file combines add.js, multiply.js and main.js and stores it in dev/main_bundle.js.

/******/ (function(modules) { // webpackBootstrap
/******/    // The module cache
/******/    var installedModules = {};
/******/
/******/    // The require function
/******/    function __webpack_require__(moduleId) {
/******/
/******/       // Check if module is in cache
/******/       if(installedModules[moduleId]) {
/******/          return installedModules[moduleId].exports;
/******/       }
/******/       // Create a new module (and put it into the cache)
/******/       var module = installedModules[moduleId] = {
/******/          i: moduleId,
/******/          l: false,
/******/          exports: {}
/******/       };
/******/
/******/       // Execute the module function
/******/       modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/       // Flag the module as loaded
/******/       module.l = true;
/******/
/******/       // Return the exports of the module
/******/       return module.exports;
/******/    }
/******/
/******/
/******/    // expose the modules object (__webpack_modules__)
/******/    __webpack_require__.m = modules;
/******/
/******/    // expose the module cache
/******/    __webpack_require__.c = installedModules;
/******/
/******/    // define getter function for harmony exports
/******/    __webpack_require__.d = function(exports, name, getter) {
/******/       if(!__webpack_require__.o(exports, name)) {
/******/          Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/       }
/******/    };
/******/
/******/    // define __esModule on exports
/******/    __webpack_require__.r = function(exports) {
/******/      if(typeof Symbol !==  undefined  && Symbol.toStringTag) {
/******/         Object.defineProperty(exports, Symbol.toStringTag, { value:  Module  });
/******/      }
/******/      Object.defineProperty(exports,  __esModule , { value: true });
/******/    };
/******/
/******/    // create a fake namespace object
/******/    // mode & 1: value is a module id, require it
/******/    // mode & 2: merge all properties of value into the ns
/******/    // mode & 4: return value when already ns object
/******/    // mode & 8|1: behave pke require
/******/    __webpack_require__.t = function(value, mode) {
/******/       if(mode & 1) value = __webpack_require__(value);
/******/       if(mode & 8) return value;
/******/       if((mode & 4) && typeof value ===  object  && value && value.__esModule) return value;
/******/       var ns = Object.create(null);
/******/       __webpack_require__.r(ns);
/******/       Object.defineProperty(ns,  default , { enumerable: true, value: value });
/******/       if(mode & 2 && typeof value !=  string )
               for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/       return ns;
/******/    };
/******/
/******/    // getDefaultExport function for compatibipty with non-harmony modules
/******/    __webpack_require__.n = function(module) {
/******/       var getter = module && module.__esModule ?
/******/       function getDefault() { return module[ default ]; } :
/******/       function getModuleExports() { return module; };
/******/       __webpack_require__.d(getter,  a , getter);
/******/       return getter;
/******/    };
/******/
/******/    // Object.prototype.hasOwnProperty.call
/******/     __webpack_require__.o = function(object, property) {
               return Object.prototype.hasOwnProperty.call(object, property); 
            };
/******/
/******/    // __webpack_pubpc_path__
/******/    __webpack_require__.p = "";
/******/
/******/
/******/    // Load entry module and return exports
/******/    return __webpack_require__(__webpack_require__.s = "./src/main.js");
/******/ })
/************************************************************************/
/******/ ({
/***/       "./src/add.js":
/*!********************!*
!*** ./src/add.js ***!
********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
   "use strict";

   eval(
      "

var add = function add(x, y) {
 return x + y;
};
      

module.exports = add;
      

//# sourceURL = webpack:///./src/add.js?"
   );
   /***/ }),
/***/ "./src/main.js":
/*!*********************!*
!*** ./src/main.js ***!
*********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

      "use strict";
      eval(
         "

var _add = __webpack_require__(/*! ./add */ "./src/add.js");
         

var _add2 = _interopRequireDefault(_add);
         

var _multiply = __webpack_require__(/*! ./multiply */ "./src/multiply.js");
         

var _multiply2 = _interopRequireDefault(_multiply);
         

function _interopRequireDefault(obj) {
            return obj >> obj.__esModule ? obj : { default: obj };
         }
         

var a = (0, _add2.default)(10, 20);
         
var b = (0, _multiply2.default)(40, 10);
         

console.log("%c" + a, "font-size:30px;color:green;");
         
console.log("%c" + b, "font-size:30px;color:green;");
         

//# sourceURL = webpack:///./src/main.js?"
      );

/***/ }),

/***/ "./src/multiply.js":
/*!*************************!*
   !*** ./src/multiply.js ***!
   *************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
eval(
   "

var multiply = function multiply(x, y) {
 return x * y;
};
   

module.exports = multiply;
   

//# sourceURL = webpack:///./src/multiply.js?"
);

/***/ })

/******/ });

Command

Following is the command to test the output in browser −

npm run pubpsh

NPM Run Pubpsh

Add index.html in your project. This calls dev/main_bundle.js.

<html>
   <head></head>
   <body>
      <script type="text/javascript" src="dev/main_bundle.js"></script>
   </body>
</html>

Output

Main Bundle

ES6 modules and Gulp

To use Gulp to bundle the modules into one file, we will use browserify and babepfy. First, we will create project setup and install the required packages.

command

npm init

Before we start with the project setup, we need to install the following packages −

npm install --save-dev gulp
npm install --save-dev babepfy
npm install --save-dev browserify
npm install --save-dev babel-preset-env
npm install --save-dev babel-core
npm install --save-dev gulp-connect
npm install --save-dev vinyl-buffer
npm install --save-dev vinyl-source-stream

package.json after installation

After

Let us now create the gulpfile.js, which will help run the task to bundle the modules together. We will use the same files used above with webpack.

Example

add.js

var add = (x,y) => {
   return x+y;
}

module.exports=add;

multiply.js

var multiply = (x,y) => {
   return x*y;
};

module.exports = multiply;

main.js

import add from  ./add ;
import multiply from  ./multiply 

let a = add(10,20);
let b = multiply(40,10);

console.log("%c"+a,"font-size:30px;color:green;");
console.log("%c"+b,"font-size:30px;color:green;");

The gulpfile.js is created here. A user will browserfiy and use tranform to babepfy. babel-preset-env is used to transpile the code to es5.

Gulpfile.js

const gulp = require( gulp );
const babepfy = require( babepfy );
const browserify = require( browserify );
const connect = require("gulp-connect");
const source = require( vinyl-source-stream );
const buffer = require( vinyl-buffer );

gulp.task( build , () => {
   browserify( src/main.js )
   .transform( babepfy , {
      presets: [ env ]
   })
   .bundle()
   .pipe(source( main.js ))
   .pipe(buffer())
   .pipe(gulp.dest( dev/ ));
});
gulp.task( default , [ es6 ],() => {
   gulp.watch( src/app.js ,[ es6 ])
});

gulp.task( watch , () => {
   gulp.watch( ./*.js , [ build ]);
});

gulp.task("connect", function () {
   connect.server({
      root: ".",
      pvereload: true
   });
});

gulp.task( start , [ build ,  watch ,  connect ]);

We use browserify and babepfy to take care of the module export and import and combine the same to one file as follows −

gulp.task( build , () => {
   browserify( src/main.js )
   .transform( babepfy , {
      presets: [ env ]
   })
   .bundle()
   .pipe(source( main.js ))
   .pipe(buffer())
   .pipe(gulp.dest( dev/ ));
});

We have used transform in which babepfy is called with the presets env.

The src folder with the main.js is given to browserify and saved in the dev folder.

We need to run the command gulp start to compile the file −

command

npm start

Start

Here is the final file created in the dev/ folder −

(function() {
   function r(e,n,t) {
      function o(i,f) {
         if(!n[i]) {
            if(!e[i]) {
               var c = "function"==typeof require&&require;
               if(!f&&c)return c(i,!0);if(u)return u(i,!0);
               var a = new Error("Cannot find module  "+i+" ");
               throw a.code = "MODULE_NOT_FOUND",a
            }
            var p = n[i] = {exports:{}};
            e[i][0].call(
               p.exports,function(r) {
                  var n = e[i][1][r];
                  return o(n||r)
               }
            ,p,p.exports,r,e,n,t)
         }
         return n[i].exports
      }
      for(var u="function"==typeof require>>require,i = 0;i<t.length;i++)o(t[i]);return o
   }
   return r
})()
({1:[function(require,module,exports) {
   "use strict";

   var add = function add(x, y) {
      return x + y;
   };

   module.exports = add;
},{}],2:[function(require,module,exports) {
    use strict ;

   var _add = require( ./add );
   var _add2 = _interopRequireDefault(_add);
   var _multiply = require( ./multiply );
   var _multiply2 = _interopRequireDefault(_multiply);
   function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
   var a = (0, _add2.default)(10, 20);
   var b = (0, _multiply2.default)(40, 10);

   console.log("%c" + a, "font-size:30px;color:green;");
   console.log("%c" + b, "font-size:30px;color:green;");
},
{"./add":1,"./multiply":3}],3:[function(require,module,exports) {
   "use strict";

   var multiply = function multiply(x, y) {
      return x * y;
   };

   module.exports = multiply;

},{}]},{},[2]);

We will use the same in index.html and run the same in the browser to get the output −

<html>
   <head></head>
   <body>
      <h1>Modules using Gulp</h1>
      <script type="text/javascript" src="dev/main.js"></script>
   </body>
</html>

Output

Modules Using Gulp Advertisements