Include one JavaScript file into another
BCiriak Avatar
by BCiriakAPR 23, 2022 | 5 min read

How to include JavaScript file into another JavaScript file?

JavaScript was never designed to be what it is today. At first, it was suppose to add tiny dynamic features to websites. Today we can build complete software solutions just with JavaScript. That is why we did not even had way to share code between two files. Let`s look at couple ways how to do it modern JavaScript.


In this article we will have a look at couple of different ways to include JavaScript files to other JavaScript files. We will do this in two environments, one is JavaScript within browser and second will be using Node.js.

If you don’t have Node installed, read how to install Node.js here.

Let’s dive in.

It was not possible to include JavaScript from another JavaScript

Back in the day, there was really no way how to include JS files. There was no mechanism to do this.

Thankfully, these days, with the extreme rise of JavaScript and module patterns, we have actually couple of ways to do this.

Two different environments

As already mentioned, we will experiment with two environments, browser or client and Node.js or server.

JavaScript in the browser

Let's imagine we are working on our plain website and want to add JavaScript, to improve our UI. We want to have one JavaScript file app.js, that is the entry point for our JS magic. Than we can have many different JavaScript files, which we would import/include into our app.js entry point. For the purpose of this simple example we will have one more JS file, xyz.js. This gives us the following folder structure:

shell
root
├── index.html
├── app.js
└── xyz.js

Let’s start with xyz.js, the file that we will import.

xyz.js
function logXyz() {
	console.log("XYZ");
}

export { logXyz };

All we do here is, we define our function called logXyz(), than export it with the export keyword and in between curly braces we specify function name/identifier to be exported. This is called named export, because we are specifically exporting by the name of our function. We could export any variable, object or class in the same way. This enables us to import the identifier in another JavaScript file. Here it goes:

app.js
import { logXyz } from "./xyz.js";

logXyz();

On the first line we import our logXyz function from xyz.js similarly to how we exported it. Since we used named export, we have to use the exported name, logXyz in between curly braces and use from keyword after which we specify path to file from which we are importing. Don’t forget the .js file extension. After this we can call the amazing function logXyz(). Now we just need to link this file from within our index.html.

index.html
<!DOCTYPE html>
<html>
	<head>
		<title>Include JS into JS</title>
	</head>
	<body>
		<h1>index.html</h1>
		<script src="app.js" type="module"></script>
	</body>
</html>

This is as basic HTML file as it gets, but pay attention to the script tag. We have to specify the type=“module” here, if we want to import our xyz.js file.

To run these examples, you will need to serve these files from server. You can install Live Server extension on your VSCode on the link below:

VSCode extension called Live Server

Now, when we serve our index.html and open up console in our browser, we will see XYZ logged. Awesome!

Include multiple functions

To have multiple functions available, we need to just add them as our identifiers like so:

xyz.js
function logXyz() {
	console.log("XYZ");
}
function logAbc() {
	console.log("ABC");
}

export { logXyz, logAbc };

And also adjust our app.js similarly:

app.js
import { logXyz, logAbc } from './xyz.js'

logXyz()
logAbc();

Exporting JavaScript functions directly

You can actually find examples that export the function directly, so let’s have a look at that example:

xyz.js
export function logXyz() {
	console.log('XYZ')
};

and the app.js

app.js
import { logXyz } from './xyz.js'

logXyz();

Pretty simple. Alright, this is how we include JavaScript files inside another JavaScript file when working with browser JavaScript. Now, let’s have a look at Node.js solutions.

Node.js doesn’t support ES6 import

Yes, it is true. At the time of writing this article, Node.js doesn’t support ES6 import. Node has its own way. Node actually relies heavily on the concept of modules. Let’s import some files in Node.js environment.

xyz.js
module.exports.sayXyz = function () {
	console.log('XYZ')
};

Here the module.exports might seem a bit confusing, but that is the Node.js module mechanism. Just think of it as an empty object, that is basically what it is (very simply put). All we do is, we append attribute to the module object and it is our sayXYZ function. Now to the app.js.

app.js
let xyz = require('./xyz')

xyz.sayXyz();

Requiring is Node way of importing. When you work with Node, you see it all over the place. Requiring modules left and right.

Interesting thing is, require returns the module.exports object with the appended attribute, which is our sayXyz function. xyz is the object in this case.

Now if we run app.js from our terminal with Node, we will get XYZ printed to the console.

shell
node app.js
> XYZ

If we want to export multiple functions, we just append another attribute to the module.exports object like so:

xyz.js
module.exports.sayXyz = function () {
	console.log('XYZ')
}

module.exports.sayAbc = function () {
	console.log('ABC')
};

Here are another two ways to the same result. First one, we make module.exports equal to the object we construct. With function attribute.

xyz.js
module.exports = {
	sayXyz: function () {
		console.log('XYZ')
	},
};

And the last one, probably the most familiar way:

xyz.js
function sayXyz() {
	console.log('XYZ')
}

module.exports.sayXyz = sayXyz;

Bonus: Node import

If you really want to use import in your Node environment, you can achieve it with the help of Babel. Babel is a JavaScript compiler that makes modern JavaScript code available in older, non-compatible JavaScript environments.

All it does with the import statement is, it transpiles the JavaScript into require function so that Node.js understands it. If you are interested in trying it out, read this nice article on Enabling Import in Node.js.

That is it for this article. Have a great one.

Keep learning and see you in the next one!

Connect with me on social media ✨

Join my newsletter, to receive JavaScript, TypeScript, React.js and more news, tips and other goodies right into your mail box 📥. You can unsubscribe at any time.

©2024 JSTopics. All rights reserved.