DEV Community

Cover image for Import, Export and Require in Javascript
Johnny Simpson
Johnny Simpson

Posted on • Updated on • Originally published at fjolt.com

Import, Export and Require in Javascript

You may have seen the following line in Javascript:

const fs = require('fs');
Enter fullscreen mode Exit fullscreen mode

And you may have then seen this..

import fs from 'fs'
Enter fullscreen mode Exit fullscreen mode

And even worse, you may have seen this:

import { promises as fs } from 'fs'
Enter fullscreen mode Exit fullscreen mode

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';
Enter fullscreen mode Exit fullscreen mode

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');
Enter fullscreen mode Exit fullscreen mode

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 straight forward 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 require is for Node.JS, and import is a Javascript/ECMAScript standard. Import uses a slightly different notation, but allows us to do roughly the same thing that 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 often 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 }
Enter fullscreen mode Exit fullscreen mode

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

import { consoller } from './general.js'
Enter fullscreen mode Exit fullscreen mode

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

import { consoller as myFunction } from 'general'
myFunction() // Runs 'consoller'
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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",
// .....
Enter fullscreen mode Exit fullscreen mode

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 frontend, it will also limit file size, by only importing what you need!

Latest comments (3)

Collapse
 
dkoppenhagen profile image
Danny Koppenhagen

I think your definition of tree shaking does not fit here. As importing just specific exports from a file is just exactly this: import exported parts. There’s nothing shaked at all.
Tree shaking is kicking out unused code during the process of bundling.
So in fact: all un-imported exports that are not used somewhere else will be completely removed when creating a code-bundle in order to reduce the code size. This is also called dead code elimination.
So it’s more about what parts of the codes will be shipped, not about the definitions of the exports itself.

Collapse
 
smpnjn profile image
Johnny Simpson

It was ambiguous, I have added the fact that it is coupled with a bundler

Collapse
 
maksympozhydaiev profile image
Maksym Pozhydaiev

It would be great to see here the different between the two approaches, for example we can call import only on the top of the fie etc.