Skip to main content

Command Palette

Search for a command to run...

ES6 module

ES6 module vs Common JS module

Updated
•2 min read•View as Markdown
ES6 module
D
Software engineer building production systems with Node.js, TypeScript, Go, and PostgreSQL. Writing about backend engineering, infrastructure, and lessons from deploying real projects.

CommonJS and ES6 modules are two different ways to organize and import JavaScript code. CommonJS modules are the older and more widely supported format, while ES6 modules are the newer and more modern format. As we all know the commonJS is all great but there are some things peculiar to the ES6 module to the commonJS which can give us a glimpse of how JS frameworks work, let's dive into the differences between both.

  1. CONNECTION:

    when linking your common JS file to your HTML document, you simply attach the src path of your common js file to the script tag.
    However, when linking an ES6 module file, you need to add a 'type' attribute that is set to 'module'

    //ES6 module file <script type = 'module' src='./ES6module.js'></script>

    //common js file

    <script src= 'commonJs.js'></script>

  2. USE STRICT:

    For the common JS file, you need to specify a "use strict" statement at the top of your JavaScript file to help identify errors. However, ES6 modules implicitly use strict mode, so you do not need to specify this statement.

    1 "use strict";

    2

    3

  3. IMPORT AND EXPORT:

    In the common JS file, we cannot import or export variables or functions(I can say "Can your Common JS ever 😅😅at this point"). However, on the ES6 module file, we can perform such.

    //import syntax

    import {age as num} from './ES6JS.js';

    //export syntax

    export {calcAge as age}

    ADVANTAGES OF USING ES6 MODULE FILE

    ES6 modules have several advantages over CommonJS modules, including:

    1. Modularity: ES6 modules are more modular than CommonJS modules, which makes them easier to understand and maintain.

    2. It helps reduce the need for so many Global variables in a project, also known as "Global namespace pollution" which can lead to unforeseen bugs.

    3. Performance: ES6 modules are often faster than CommonJS modules because they can be loaded and executed asynchronously.

    4. Security: ES6 modules are more secure than CommonJS modules because they can be sandboxed.

    5. Finally, It makes our project look professional

      Conclusion

      ES6 modules are the newer and more modern way to organize and import JavaScript code. They offer several advantages over CommonJS modules, including modularity, performance, and security. If you are working on a new JavaScript project, I recommend using ES6 modules.

      I hope this helps! Let me know if you have any other questions.