DZone
Web Dev Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Web Dev Zone > Import, Export, and Require in JavaScript

Import, Export, and Require in JavaScript

In this article, we will finally understand exactly what import, export, and require all do in JavaScript. Additionally, we'll understand when and why should we use them.

Johnny Simpson user avatar by
Johnny Simpson
CORE ·
Feb. 08, 22 · Web Dev Zone · Tutorial
Like (3)
Save
Tweet
6.93K Views

Join the DZone community and get the full member experience.

Join For Free

Today, we are going to learn about JavaScript import, export, and require, when and why we use them, and why we have two ways to do it in the first place.

Let's get started!

You may have seen the following line in JavaScript:

 
const fs = require('fs');


And you may have then seen this:

 
import fs from 'fs'


And even worse, you may have seen this:

 
import { promises as fs } from 'fs'


What does all of this mean?! And why are there so many ways to seemingly import packages in JavaScript? And why can't I get import to work on my Node.JS server? Let's explore what it all means.

Import, Export, and Require in JavaScript

Out of the box, when you are writing in JavaScript in Node.JS, require() works like a charm. That's because require was built for Node.JS specifically. If a file exports something, then require will import that export. Suppose we have a package called 'general' with an index.js file like this:

 
export.consoller = function(msg) {
    console.log(msg);
}
export.adder = function(x, y) {
    return x + y;
}
export.name = 'Some Name';


This format, using export.[function] is NPM specific. It was built to work with NPM, and so is a bespoke part of Node.JS, not aligned to any particular standard. To import those functions, we can easily use require:

 
const general = require('general');


Any exports we have can now be accessed. In the example above where we used export.name, we can now access it via general.name in our code. This is one of the most straightforward ways to add packages with Node.JS.

The important thing to remember is require and import are two totally separate pieces of functionality. Don't get confused by the way we export code with require!

Import in Javascript

The difference between import and require is that require is for Node.JS, and the import is a JavaScript/ECMAScript standard. The import uses a slightly different notation but allows us to do roughly the same thing that the require does.

The import standard gives us a bit more flexibility and works in such a way that we can import specific pieces of functionality. This is called tree-shaking when coupled with a bundler like Webpack, allowing us to load just the Javascript we want, rather than the entire file. To start, let's look at a simple example of how you export and import a function.

First, let's presume we have a file called general.js. This is our export file. Let's export some functions using the export keyword.

 
const consoller = function(msg) {
    console.log(msg);
}
const adder = function(x, y) {
    return x + y;
}
const name = 'Some Name';

export { consoller, adder, name }


Now when we import, we can import only part of this module. For example:

 
import { consoller } from './general.js'


Now we only need to reference consoller, and can reference it as consoller(). If we didn't want that, we could import consoler as something else, i.e:

 
import { consoller as myFunction } from 'general'
myFunction() // Runs 'consoller'


Importing a Default in Javascript

If in our export file, we name a default export, that export will be included as whatever we want. So for example, let's say we do the following:

 
let functionList = {}

functionList.consoller = function(msg) {
    console.log(msg);
}
functionList.adder = function(x, y) {
    return x + y;
}
functionList.name = 'Some Name';
    
export default functionList;


Now when we import, we can import functionList and name it as anything we like in the following format:

 
import myStuff from './general.js';
myStuff.consoller() // Our consoller function


Import * As in JavaScript

Another thing we can do is import everything and name it something else. For example, we can do this:

 
import * as functionSet from './general.js';
functionSet.consoller(); // Runs our consoller function


Why Is Import Not Working in Node.JS for Me?

Import is a new-ish standard, so it won't work exactly how you expect right out of the box. Make sure you've got at least Node.JS version 12 installed. Then, we need to update our package.json. If you don't have one, run npm init on your command line in the folder, you're working in.

Change your package.json to have the line "module":"true", as shown below:

 
// .....
"name": "Fjolt",
"type": "module", /* This is the line you need to add */
"repository": {
    "type": "git",
    "url": "..."
},
"author": "",
"license": "ISC",
// .....


Now modules will work by default in your Node.JS directory. There is a catch though - and that is that now require() will not work - so make sure you've fully converted over to import before making this change.

Conclusion

So, require is a custom-built solution, while import/export is a Javascript standard. require was written originally because import didn't exist, and Node.JS needed a way to insert packages easily. Later on, the group that oversees JavaScript's development put forward the proposal for import. In other words, Node.JS wanted to do something fast, so invented their own methodology.

Now that we have import (which is better and more fleshed out than require), I would recommend using it if you can. Since it's a standard, it means you can use it in both frontend and backend development, and it will give you more options for importing and exporting your packages. If you do anything in the front-end, it will also limit file size, by only importing what you need!

JavaScript Node.js

Published at DZone with permission of Johnny Simpson, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Anatomy of a Webhook HTTP Request
  • Remote Debugging and Developer Observability
  • Build a Data Pipeline on AWS With Kafka, Kafka Connect, and DynamoDB
  • Event-Driven Hello World Program

Comments

Web Dev Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo