Skip to main content

Command Palette

Search for a command to run...

L2. Node.js Modules & Import/Export

Published
โ€ข1 min readโ€ขView as Markdown

1. Initializing a Project

npm init -y
  • Automatically generates package.json without asking for details.

2. What are Modules?

  • Functions saved in different files and imported where needed.

  • Helps organize code better.

3. Writing and Using Modules

Creating a Module (util.js)

// Define functions
export const sub = (a, b) => a + b;  
export const mul = (a, b) => a * b;
  • Export functions directly using export.

Importing in index.js

import { sub, mul } from "./util.js";  

console.log("Subtraction:", sub(2, 1));
  • Use ES Module Import (import {}) instead of require().

4. Switching to ES Modules

  • In package.json, add:
"type": "module"
  • Enables ES Module syntax (import/export).

5. Alternative (CommonJS Syntax)

If using CommonJS (default in Node.js):

Exporting in util.js

const sub = (a, b) => a + b;  
const mul = (a, b) => a * b;  

module.exports = { sub, mul };

Importing in index.js

const { sub, mul } = require("./util");

More from this blog

N

Nodejs

12 posts