DEV Community

Vinay Madan
Vinay Madan

Posted on

import vs require in JS

The most common question that is asked is, What are the key differences between import vs require in Javascript?

  • Import and Export are ES6 features(Next gen JS).
  • Require is old school method of importing code from other files

Image description

This simple image will help to you understand the differences between require and import.

Loading is synchronous(step by step) for require on the other hand import can be asynchronous

The major difference is in require, entire JS file is called or included. Even if you don't need some part of it.

var myObject = require('./otherFile.js'); //This JS file will be included fully.

Whereas in import you can extract only objects/functions/variables which are required.

import { getDate }from './utils.js';

//Here I am only pulling getDate method from the file instead of importing full file

Another major difference is you can use require anywhere in the program where as import should always be at the top of file

Edit: In Latest node versions you can use destructuring. It will look like this

const { getDate } = require('./date.js');

Top comments (0)