DZone
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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Deno vs. Node.js: The Showdown Nobody Asked For But Everyone Needed
  • Building a Tic-Tac-Toe Game Using React
  • Buh-Bye, Webpack and Node.js; Hello, Rails and Import Maps
  • Bridging JavaScript and Java Packages: An Introduction to Npm2Mvn

Trending

  • Apache Doris vs Elasticsearch: An In-Depth Comparative Analysis
  • How to Practice TDD With Kotlin
  • While Performing Dependency Selection, I Avoid the Loss Of Sleep From Node.js Libraries' Dangers
  • A Guide to Container Runtimes
  1. DZone
  2. Coding
  3. JavaScript
  4. 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.

By 
Johnny Simpson user avatar
Johnny Simpson
DZone Core CORE ·
Updated Feb. 08, 22 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
8.0K 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.

Related

  • Deno vs. Node.js: The Showdown Nobody Asked For But Everyone Needed
  • Building a Tic-Tac-Toe Game Using React
  • Buh-Bye, Webpack and Node.js; Hello, Rails and Import Maps
  • Bridging JavaScript and Java Packages: An Introduction to Npm2Mvn

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!