Table of Contents
But I'm not using Angular. I just want to convert the ES6 module to CommonJS/AMD
What is the purpose of using Babel and Gulp to translate ES6 modules into AMD and CommonJS?
How does Babel help translate ES6 modules?
What role does Gulp play in the translation process?
Can I translate the ES6 module to AMD instead of CommonJS?
What is the difference between AMD and CommonJS?
How to specify the ES6 feature to be translated?
What are the benefits of using ES6 modules?
How to debug translated code?
Can I use Babel and Gulp with other JavaScript frameworks?
Are there any alternatives to Babel and Gulp for translation of ES6 modules?
Home Web Front-end JS Tutorial Transpiling ES6 Modules to AMD & CommonJS Using Babel & Gulp

Transpiling ES6 Modules to AMD & CommonJS Using Babel & Gulp

Feb 19, 2025 pm 12:46 PM

Transpiling ES6 Modules to AMD & CommonJS Using Babel & Gulp

Core points

  • ECMAScript 6 (ES6) has made a lot of improvements to JavaScript to better suit its current scale of use, including the ability to load different parts of the application in the form of modules. However, not all browsers have implemented all ES6 features, and that's where translators like Babel and Traceur come into play.
  • Babel and Gulp can be used to translate ES6 modules into CommonJS or AMD, enabling them to be read by today's browsers. This process involves using Babel's Gulp task to convert modules into one of the existing module systems, and then package the application into a single file for the browser to use.
  • CommonJS is a synchronous module system used by Node.js, which loads modules using the require function and exports them using the exports property of the module object. Converting an ES6 module to CommonJS involves the use of a combination of Babel, Browserify, and Gulp.
  • Async Module Definition (AMD) system allows multiple dependent modules to be loaded in parallel. To convert the ES6 module to AMD, we use Babel, RequireJS, and Gulp. You can then directly reference the final script on the index.html page and view it in the browser.

ECMAScript 6 (aka ECMAScript 2015 or ES6), the specification for the next version of JavaScript has been approved and browser vendors are working to implement it. Unlike previous versions of ECMAScript, ES6 has made a huge change to the language, allowing it to adapt well to today's usage scale. Sitepoint has several articles covering these features.

Although the browser has not implemented all the features yet, we can still take advantage of ES6 during development and convert the application into a version that the browser can understand before delivering it. Babel and Traceur are two of the leading translators used for this purpose. Microsoft's JavaScript type superset TypeScript can also be used as an ES6 translator.

In a previous article, I explained how to use ES6 to write Angular 1.x applications. In that post, I used Traceur's instant translator to run the application. While it works, it is best to translate in advance and reduce the amount of work that needs to be done in the browser. In this article, we will see how to translate the same sample application to ES5 and convert the module to CommonJS or AMD, using Babel to enable it to run on today's browsers. Although the examples are based on Angular, translation techniques can be used for any valid ES6 code.

As always, you can find the accompanying code for this article in our GitHub repository.

The importance of modules

In any language used to write large applications, a key feature is the ability to load different parts of an application in the form of modules. Modules not only help make the code more concise, but also play a role in reducing the use of global scope. The contents of the module are not provided to any other module unless it is explicitly loaded.

The importance of modules is not limited to applications. Even large JavaScript libraries can use module systems to export their objects as modules, and applications using these libraries can import these modules as needed. Angular 2 and Aurelia have started using this feature.

If you want a quick look at how to use modules in ES6, read: Understanding ES6 Modules

About the sample application

The theme of our sample application is virtual bookshelf. It contains the following pages:

  1. Home: Displays a list of active books that can be marked as read or moved to archive.
  2. Add Book Page: Add new books to the bookshelf by accepting the book title and author name. It does not allow duplicate titles.
  3. Archive page: List all archived books.

The application is built using AngularJS 1.3 and ES6. If you look at any files in the app folder, you will see the keywords export and import for exporting objects from the current module and importing objects from other modules. Now, our job is to convert these modules into one of the existing module systems using Babel's Gulp task.

But I'm not using Angular. I just want to convert the ES6 module to CommonJS/AMD

Don't worry! We're ready for you. With just a small amount of tweaking, the recipe demonstrated below can be used on any project involving an ES6 module. Angular doesn't matter here.

Convert to CommonJS

CommonJS is a module system defined by the CommonJS group. It is a synchronous module system where the module is loaded using the require function and the module is exported using the exports property of the module object. Module objects should be available in all modules by default.

Node.js uses this module system, so it natively defines the module object and provides it to your application. Since the browser does not define this object, we need to use a utility called Browserify to fill in the gap.

We also need to install some npm packages before we start. This will allow us to use Babel and Browserify with Gulp to convert our ES6 modules into one of the common module formats and package the application as a single file for the browser to use.

  • gulp-babel — Convert ES6 code to normal ES5
  • Browserify — allows you to require('modules') in your browser by bundling all dependencies
  • vinyl-source-stream — Handle the Browserify module directly to avoid the need for gulp-browserify wrapper
  • vinyl-buffer — Convert streams to buffers (necessary for gulp-uglify that does not support streams)
  • gulp-uglify — Compressed file
  • del — Allows you to delete files and folders
  • gulp-rename — A plugin that allows you to rename files

You can get all of this by typing:

<code>npm install gulp-babel browserify gulp-browserify vinyl-source-stream vinyl-buffer gulp-uglify del gulp-rename --save-dev</code>
Copy after login

Now let's start using these packages in our gulpfile.js. We need to write a task to get all ES6 files and pass them to Babel. The default module system in Babel is CommonJS, so we don't need to send any options to the babel function.

<code>var babel = require('gulp-babel'),
    browserify = require('browserify'),
    source = require('vinyl-source-stream'),
    buffer = require('vinyl-buffer'),
    rename = require('gulp-rename'),
    uglify = require('gulp-uglify'),
    del = require('del');

gulp.task('clean-temp', function(){
  return del(['dest']);
});

gulp.task('es6-commonjs',['clean-temp'], function(){
  return gulp.src(['app/*.js','app/**/*.js'])
    .pipe(babel())
    .pipe(gulp.dest('dest/temp'));
});
</code>
Copy after login

Hope there is nothing too confusing here. We are declaring a task called es6-commonjs that gets any JavaScript file in the app directory and any subdirectories. It then passes them through Babel, which in turn converts individual files to ES5 and CommonJS modules and copies the converted files to the dest/temp folder. The es6-commonjs task has a dependency called clean-temp which will delete the dest directory and any files in it before the es6-commonjs task runs.

If you want to make the code clearer and specify the module system, you can modify the usage of Babel as follows:

<code>.pipe(babel({
  modules:"common"
}))
</code>
Copy after login

Now we can create a single bundle file from these single files by applying Browserify and compressing the output using the uglify package. The following code snippet shows this:

<code>gulp.task('bundle-commonjs-clean', function(){
  return del(['es5/commonjs']);
});

gulp.task('commonjs-bundle',['bundle-commonjs-clean','es6-commonjs'], function(){
  return browserify(['dest/temp/bootstrap.js']).bundle()
    .pipe(source('app.js'))
    .pipe(buffer())
    .pipe(uglify())
    .pipe(rename('app.js'))
    .pipe(gulp.dest("es5/commonjs"));
});
</code>
Copy after login

The above task has two dependencies: the first is the bundle-commonjs-clean task, which will delete the es5/commonjs directory; the second is the es6-commonjs task discussed earlier. After these tasks are run, the task puts the combined and compressed file app.js into the es5/commonjs folder. This file can be referenced directly in index.html and the page can be viewed in the browser.

Finally, we can add a task to start the operation:

<code>gulp.task('commonjs', ['commonjs-bundle']);
</code>
Copy after login

Convert to AMD

Async module definition (AMD) system, as the name implies, is an asynchronous module loading system. It allows multiple dependent modules to be loaded in parallel, and it does not wait for one module to be fully loaded before attempting to load other modules.

Require.js is a library used to handle AMD. RequireJS is available through Bower:

<code>bower install requirejs --save</code>
Copy after login

We also need the Gulp plugin of Require.js to bundle the application. To do this, install the gulp-requirejs npm package.

<code>npm install gulp-requirejs --save-dev</code>
Copy after login

Now, we need to write a task that converts ES6 code to ES5 and AMD and then bundles it with RequireJS. These tasks are very similar to those created in the CommonJS section.

<code>var requirejs = require('gulp-requirejs');

gulp.task('es6-amd',['clean-temp'], function(){
    return gulp.src(['app/*.js','app/**/*.js'])
    .pipe(babel({ modules:"amd" }))
    .pipe(gulp.dest('dest/temp'));
});

gulp.task('bundle-amd-clean', function(){
  return del(['es5/amd']);
});

gulp.task('amd-bundle',['bundle-amd-clean','es6-amd'], function(){
  return requirejs({
    name: 'bootstrap',
    baseUrl: 'dest/temp',
    out: 'app.js'
  })
  .pipe(uglify())
  .pipe(gulp.dest("es5/amd"));
});

gulp.task('amd', ['amd-bundle']);
</code>
Copy after login

To use the final script on the index.html page, we need to add a reference to the RequireJS, the generated script, and then load the bootstrap module. The bootstrap.js file inside the app folder boots the AngularJS application, so we need to load it to start the AngularJS application.

<code> src="bower_components/requirejs/require.js" >>
 src="es5/amd/app.js">>
>
  (function(){
    require(['bootstrap']);
  }());
>
</code>
Copy after login

Conclusion

Modules are a feature that JavaScript has long lacked. They will appear in ES6, but unfortunately, their current native browser support is poor. But that doesn't mean you can't use them today. In this tutorial, I demonstrate how to convert ES6 modules to CommonJS and AMD formats that can run in the browser using Gulp, Babel, and various plugins.

As for ES6? Since its release, ES6 has gained a lot of attention in the community. It has been used by JavaScript plug-ins including Bootstrap, Aurelia, Angular 2, and many other JavaScript libraries or frameworks. TypeScript also adds support for some ES6 features, including modules. Learning and using today’s ES6 will reduce the effort required to convert code in the future.

FAQs (FAQs) for Translating ES6 Modules to AMD and CommonJS using Babel and Gulp

What is the purpose of using Babel and Gulp to translate ES6 modules into AMD and CommonJS?

Using Babel and Gulp to translate ES6 modules into AMD and CommonJS is a process that allows developers to write code using the latest version of JavaScript (ES6) and then convert it into a version that various JavaScript engines can understand. This is especially useful because not all browsers or environments support the latest ES6 features. By translating the code, developers can ensure that their applications run smoothly on different platforms.

How does Babel help translate ES6 modules?

Babel is a JavaScript compiler that is mainly used to convert ECMAScript 2015 (ES6) code into backwards-compatible JavaScript versions that can be run by older JavaScript engines. When translating ES6 modules, Babel provides plugins like "babel-plugin-transform-modules-commonjs" that convert ES6 module syntax to widely supported CommonJS syntax.

What role does Gulp play in the translation process?

Gulp is a task runner that can be used to automate the translation process. It can be configured to monitor any changes in an ES6 file and automatically run the Babel translator on it. This allows developers to manually run the translator every time they change the code.

Can I translate the ES6 module to AMD instead of CommonJS?

Yes, you can translate ES6 modules into asynchronous module definitions (AMD) instead of CommonJS. Babel provides a plugin called "babel-plugin-transform-modules-amd" for this purpose. AMD is especially useful when dealing with a large number of modules in a web browser environment.

What is the difference between AMD and CommonJS?

AMD and CommonJS are both module formats. The main difference between them is how they handle dependencies. AMD supports asynchronous loading of dependencies, which can improve performance in browser environments. CommonJS, on the other hand, loads dependencies synchronously, which is simpler and works well in server environments like Node.js.

How to specify the ES6 feature to be translated?

Babel Use a configuration file named .babelrc (or babel.config.js), where you can specify the ES6 functionality to be translated. You can list the plugins or presets to use in this file. For example, to translate an ES6 module, you will include "babel-plugin-transform-modules-commonjs" or "babel-plugin-transform-modules-amd" in the configuration.

What are the benefits of using ES6 modules?

ES6 modules bring many benefits to JavaScript development. They introduce a standard syntax for importing and exporting functions, objects, or values ​​from modules, which can make your code more organized and manageable. They also support static analysis, which improves performance and catches errors at compile time rather than runtime.

How to debug translated code?

Debugging translated code can be challenging because the code executed is different from the one you wrote. However, Babel provides a solution to this problem through the form of source mapping. A source map is a file that maps the translated code back to the original source code, allowing you to debug the code just as it is running the original ES6 code.

Can I use Babel and Gulp with other JavaScript frameworks?

Yes, Babel and Gulp are not bound to any specific JavaScript framework. They can be used with any ES6-enabled framework, including React, Angular, Vue.js, and more.

Are there any alternatives to Babel and Gulp for translation of ES6 modules?

Yes, there are several alternatives for Babel and Gulp that can be used to translate ES6 modules. These include TypeScript, Traceur, and Rollup. These tools each have their pros and cons, so the best choice depends on your specific needs and preferences.

The above is the detailed content of Transpiling ES6 Modules to AMD & CommonJS Using Babel & Gulp. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles