What is the default import and named import in Javascript? - Free Web Development || UI Development || React JS || Angular

Latest

Free Web Development ||Free UI Development || React JS || HTML5 || CSS3 || JavaScript || Angular Learn Web Development || Frontend Developer || Full Stack Developer

1 / 3
Welcome to Shravan Ghanchi
2 / 3
3 / 3

Wednesday, May 14, 2025

What is the default import and named import in Javascript?

 

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 (require)

    ES Modules (import)

    Module System

    Used in Node.js

    Used in modern JS (ES6+)

    Loading Behavior

    Synchronous (blocking)

    Asynchronous (non-blocking)

    Export/Import Type

    Supports module.exports

    Supports export and export default

    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 type: module in package.json

    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

    Snow
    Forest
    Mountains
    Snow
    Forest
    Mountains