Module Type in package.json Explained

Why ES Modules?

By default, Node.js uses CommonJS syntax (require, module.exports).

If you try:

import express from 'express';

You'll get an error, because Node doesn’t recognize import/export without proper setup.


Enable ES Module Support

In your package.json, add this line:

"type": "module"

This tells Node.js to interpret your files using ES module syntax.


Before (CommonJS Syntax)

const express = require("express")();


After (ES Module Syntax)

import express from 'express';
const app = express();


Create Pages Using Export/Import

Create home.js

pages/home.js

export default function home() {
return `<h1>Home Page with ES export way</h1>`;
}


Create about.js

File: pages/about.js

export default function about() {
return `<h1>About Page</h1>`;
}


Create contact.js

pages/contact.js

export default function contact() {
return `<h1>Contact Page</h1>`;
}


Import and Use in Your Main File

File: index.js

import express from 'express';
import home from './pages/home.js';
import about from './pages/about.js';
import contact from './pages/contact.js';

const app = express();

app.get("/", (req, res) => {
res.send(home());
});

app.get("/about", (req, res) => {
res.send(about());
});

app.get("/contact", (req, res) => {
res.send(contact());
});

app.listen(3200);