In this post, we will cover standard JavaScript modules, how we generally use them today in frontend apps, and how we may be using them in the future. JavaScript modules are sometimes referred to as ESM, which stands for ECMAScript modules.

JavaScript Modules in 2020

What are JavaScript modules?

JavaScript modules are a way to structure JavaScript code. Code in a module is isolated from code in other modules and is not in the global scope.

<script>
  function hello() {
    console.log("hello Bob");
  }
</script>
<script>
  function hello() {
    console.log("hello Fred");
  }
</script>
<script>
  hello(); // outputs hello Fred
</script>

The above code demonstrates two functions, not using modules, in the global scope colliding.

The other problem that JavaScript modules solves is not having to worry about the ordering of script elements on a HTML page:

<script>
  hello(); // 💥 - Uncaught ReferenceError: hello is not defined
</script>
<script>
  function hello() {
    console.log("hello");
  }
</script>

In the above example, the script element that contains the hello function needs to placed before the script element that invokes hello for it to work. This is hard to manage if there are lots of JavaScript files.

How JavaScript modules are commonly used today

The JavaScript module syntax was introduced in ES6 and is commonly used in apps we build today as follows:

import React from 'react';
...
export const HomePage = () => ...

The above example imports the React module and exports a HomePage component.

This code isn’t using JavaScript modules natively though. Instead, Webpack transpiles this into non-native modules (IIFEs). It’s worth noting that Webpack does have an experimental outputModule feature that allows it to publish to native module format. Hopefully this will be included in Webpack 5!

Using JavaScript modules natively

To declare a script element that references code from a JavaScript module, it needs a type attribute set to "module":

<script type="module">
  import { hello } from "/src/a.js";
  hello();
</script>

Here’s the JavaScript from a.js, in the src folder:

// /src/a.js
import { hellob } from "/src/b.js";
import { helloc } from "/src/c.js";

export function hello() {
  hellob();
  helloc();
}

So, the hello function in a.js calls hellob in b.js and helloc in c.js.

#javascript #modules #programming

JavaScript Modules in 2020
1.90 GEEK