DEV Community

Kenneth Lum
Kenneth Lum

Posted on

What are the types of module in JavaScript?

Why

allow code of different authors to work well together

Main goal

  • Encapsulation
  • Hiding private details from global scope

Methods

  • DIY by using closure, object, class
  • Node.js using require()
  • ES6 using import and export

Using DIY Closure

usually by IIFE, so that everything is inside of that function scope

Using Node.js require()

To export

    exports.foo = …
Enter fullscreen mode Exit fullscreen mode

or to export a single item

    modules.exports = …
Enter fullscreen mode Exit fullscreen mode

To import

const http = require("http");
const stats = require("./stats.js");
Enter fullscreen mode Exit fullscreen mode

webpack can use this format too… although, it might be better just to use the ES6 import and export

ES6 import export

  • each file is a module
  • all things private to the module unless explicitly exported

Export

all over the code, or at the end using one export keyword for things to export

export foo = 123;
export function bar() { … }
export class Wah…
Enter fullscreen mode Exit fullscreen mode

Or, at the very end,

export { foo, bar, Wah };
Enter fullscreen mode Exit fullscreen mode

Export Default

This is so that other modules can easily import it using

import Foo from "...";
Enter fullscreen mode Exit fullscreen mode

and it was exported by

export default Foo;
Enter fullscreen mode Exit fullscreen mode

Import

Import the default by

import Foo from "./Foo.js";
Enter fullscreen mode Exit fullscreen mode

Import multiple exports by

import { foo, bar } from "./Foo.js"
Enter fullscreen mode Exit fullscreen mode

Possible but a little uncommon to import both

import Foo, { bar, wah } from "./Foo.js"
Enter fullscreen mode Exit fullscreen mode

Import renaming

import Foo as Bar from "./Foo.js"
Enter fullscreen mode Exit fullscreen mode

It is possible to re-export too.

For more info, can refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

Top comments (0)