const {sample } = require('somefilepath')--> Named import
const data = require('somefilepath')--> Default import
import {sample} from 'somefilepath'---> Named import
import data from 'somefilepath'--> Default import
what is the difference in all four import ?
-------------------------------------------------------
These four statements represent two different module systems in JavaScript: CommonJS (require
) and ES Modules (import
). Let’s break them down:
1. CommonJS Syntax (require
)
Used in Node.js and older JavaScript environments:
const { sample } = require('somefilepath'); // Named import using object destructuring
const data = require('somefilepath'); // Default import (entire module)
require()
is synchronous and loads the module at runtime.{ sample }
retrieves only the sample
function/property from the module.data
loads the entire exported object or function from the module.2. ES Modules Syntax (import
)
Used in modern JavaScript (ES6+), especially in browsers:
import { sample } from 'somefilepath'; // Named import (specific function/property)
import data from 'somefilepath'; // Default import (entire module)
import
works asynchronously and must be used with type="module"
in ESM (ECMAScript Modules).{ sample }
is a named export, meaning the module file explicitly exported sample
.data
is a default export, meaning the module exported a single entity.Key Differences
Feature | CommonJS ( | ES Modules ( |
---|---|---|
Module System | Used in Node.js | Used in modern JS (ES6+) |
Loading Behavior | Synchronous (blocking) | Asynchronous (non-blocking) |
Export/Import Type | Supports | Supports |
Can be used in Browsers? | No (without bundlers) | Yes (modern browsers support ESM) |
Can be used in Node.js? | Yes (default) | Yes, but only if |
When Should You Use Each?
- Use CommonJS (
require
) when working with older Node.js projects or modules that don’t support ESM. - Use ES Modules (
import
) for modern JavaScript applications, especially in browsers or newer Node.js projects.
No comments:
Post a Comment