JavaScript Concept 12 - Modules in JavaScript (CommonJS, Babel & Webpack)

Why Module is important?

  • Reusability
  • Composability
  • Leverage
  • Isolation (Easy to maintain)
  • Organization

CommonJS

CommonJs is one of the standards which NodeJS has been using. Before ES6, browsers didn’t support module system. Basically Syntaxs like CommonJS and AMD made it possible for browsers and server engines to use module system.

This is how the module system works in CommonJS.

// greeting.js

let hello = function() {
  console.log('hello')
}

exports.greeting = hello
// example.js

let greeting = require('./greeting.js')
greeting.hello() // 'hello'

Babel & Webpack

Though ES Modules now landed in the browsers, there are some old versions of browsers or servers that don’t understand the syntax of ES Modules. To make our codes compatible for those environments, transpiling process (put simply, translating es6 syntax to es5) is necessary.

The well-known ones are babel and bundling tool, webpack. A JavaScript bundler gathers the separated codes into one .js file and you can set it up for es5 conversion as well if there are codes written in es6.

Conclusion

Transpilers are still needed for a smooth unification of client-side code and on server-side(NodeJS) code.



Reference

https://flaviocopes.com/es-modules/




RossenaHuh
Written by@RossenaHuh
Fast learning Web Developer with interests in state-of-art technologies & a person who continuously seeks for diversity and better communications in life.

GitHub