본문 바로가기

Web/Javascript

Import vs. Require

Import

import express from "express";

- import modules in ES6

- async operation -> the script won't be blocked while the module is loading

(ex)

import * as myModule from "myModule";

OR

import { myMethod, myMethod2 } from "myModule";


Require

const express = require("express");

- import modules in Node.js

- sync operation -> block the code execution until the module is loded and ready

(ex)

const WebSocketServer = require("ws").WebSocketServer;

OR

const ws = require("ws")

ws.WebSocketServer( ... )

OR

const { WebSocketServer } = require("ws")

 

 

** 

to use import syntax, have to add "type": "module" on package.json file 

CANNOT mix import and require syntax⭐️