Menu Home

import

Hi everyone, and welcome to another side-splitting adventure in Boring JavaScript! Today, we tackle the import statement. With it, you can import modules and objects from other JavaScript files – which is very convenient when you have all your business logic located across multiple JavaScript files and you don’t want to have one giant JS file to read in and process.

Don’t like to read? Then watch our video.

Where’s My Function?

The import statement works best with files that contain the export statement, so these two statements are linked together (for the most part – there are exceptions. Check out the MDN documentation on importing side effects). The basic construct is that you write a JavaScript file that exports functions (or data, for that matter), and then write another JavaScript file that imports that function for use. Let’s take a look at one:

// Animal.js
export default class Animal {
	name = "";
	type = "";
	age = 0;
	constructor(args) {
		const { name, type } = args;
		this.name = name;
		this.type = type;
		this.age = Math.floor(Math.random() * 10) + 2;
	}

	toSuperString () {
		return `The animal's name is "${this.name}", its type is a "${this.type}, and its age is ${this.age} years old."`;
	}
}

// import.js
import Animal from './ImportAnimal.js';

const myCat = new Animal({ name: 'Fluffy', type: 'Cat'});
console.log(myCat.toSuperString());

Here, we have a file called ‘Animal.js’ that exports the class ‘Animal’. Then, in the file ‘import.js’, we use the import statement (Line 19) to read in the exported ‘Animal’ class. From that point, ‘Animal’ is now a class that can be instantiated within the ‘import.js’ file – as if ‘Animal’ was defined within ‘import.js’ (line 21).

And that’s why the import statement is so wonderful. You can now define a class within its own JavaScript file and import that class into any other JavaScript file which may need it. Gone are the days that you had all your classes defined within the same JavaScript file. With each one having its file, you only need to bring in what you need. A great savings in time and memory.

One Potato, Two Potato, Three Potato, Four

You can import one object from another file, but you can also import multiple objects from the same file. Consider the following:

// zoo.js
const entrance = () => {
	console.log('Welcome to the Zoo!');
}

const egress = () => {
	console.log('This way to the Egress!');
}

const type = (animal) => {
	return {
		cat: "Feline",
		dog: "Canine",
		whale: "Really Big Animal"
	}[animal.type];
}

export { entrance, egress, type };

// myzoo.js
import {entrance, egress, type } from './zoo.js';

const cat = { type: 'cat', name: 'Fluffy' };
const dog = { type: 'dog', name: 'Rover' };
const whale = { type: 'whale', name: 'Moby Dick' };

entrance();
console.log(`I have a ${type(cat)}.`);
console.log(`I have a ${type(dog)}.`);
console.log(`I have a ${type(whale)}.`);
egress();

/* output
Welcome to the Zoo!
I have a Feline.
I have a Canine.
I have a Really Big Animal.
This way to the Egress!
*/

Here, the file ‘zoo.js’ exports three functions (instead of just one). It’s now up to our importing module to grab those three functions and make them available to our code. Instead of importing one function, we import multiple functions by wrapping the variables within curly-cue brackets (Line 21). Each exported function from ‘zoo.js’ will now be available to use as normal functions within our code (Lines 27 – 31).

J.J. says “Dy-No-Matically”

The examples above shows what is called a ‘static’ import. That is the preferred method of importing functions and variables from other JavaScript files. But JavaScript does give you the ability to import files dynamically, and that’s by using the import statement as a function. Why would you want to do this? Let’s say you setup a survey on people’s favorite foods. Each category of food has it’s own separate set of questions, so you really don’t want to load them all into your survey if you’re going to only process one.

To solve this, you will dynamically load in the correct survey once the type of survey has been determined.

async function getSurvey(surveyName) {
    const { default: Survey } = await import(`./survey-${surveyName}.js`);
    return Survey;
}

getSurveyName()
    .then(getSurvey)
    .then(displaySurvey)

In the above code, the ‘getSurvey’ function uses the dynamic import (Line 2) to load in only the survey requested by the user.

If you want to see an actual working example, check out our video.

Video

As always, here is a video showing how imports work.

Shameless Plug

Check us out everywhere!

Check out all our videos at: https://www.boringjavascript.com

Check out everything at: https://www.thevirtuoid.com

Facebook: https://www.facebook.com/TheVirtuoid

Twitter: https://twitter.com/TheVirtuoid

YouTube: https://www.youtube.com/channel/UCKZ7CV6fI7xlh7zIE9TWqgw

Categories: Boring JavaScript Javascript

Tagged as:

thevirtuoid

Web Tinkerer. No, not like Tinkerbell.

Creator of the game Virtuoid. Boring JavaScript. Visit us at thevirtuoid.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: