Skip to content

TodayILearned - 2023-04-03

Posted on:April 3, 2023 at 02:39 AM

TIL

Today’s TIL is based on a post on bundler, ES, Common JS modules written by Eunjae, my dear friend and web developer. I’ve always been confused by require and import so wanted to quickly jot down notes.

CommonJS’s Module System:

// myModule.js
const sayHi = () => {
  console.log("Hello World");
};
module.exports = { sayHi };

// app.js
const myModule = require("./myModule.js");
myModule.sayHi(); // Hello World

ES Module System:

// myModule.js
export const sayHi = () => {
  console.log("Hello World");
};

// app.js
import { sayHi } from "./myModule.js";
myFunc(); // Hello World

I had previously said in my post on destructuring that these import statements contain destructuring. I’ve learned since than through the feedback from Eunjae(merci!) and some googling that my statement wasn’t entirely accurate. While the curly braces in the import statement are SIMILAR to destructuring syntax in that they are extracting something specific from a larger structure or object, they are not entirely the same.

The {} within the import statement is specifying the names of the exports you want to load from the module. This means that if the module has a default export function, you don’t need to use {} to load it. (Note to self: a module can only have ONE default export, but as many named exports as you like).

Because browsers don’t have import and require, you typically need a bundler to ‘bundle’ the code from different files together and remove those require and import statements to ensure your code will work on the browser. That being said, for some modern browsers, if you specify type="module" in the <script> tag, you can use the import syntax.