Traditional JavaScript applications used to contain very few ‘js’ files and the developers used to put huge amount of code in a single JavaScript file. Now as the things are changing, modularity is becoming one of the core principle of modern applications where we divide the application into several as much small as possible modules. So, we may often want to access data from one file in another file. There are couple of ways to do this.

Using Traditional ES5 JavaScript:

In traditional ES5 JavaScript, there was no support for modularity. To work with different files, developers used to import the files using the script tag. The order of these imports are important and the file that depends on the data from another file must come later.

example:

001.js

Copy to Clipboard

002.js

Copy to Clipboard

index.html

Copy to Clipboard

If we run the index.html by keeping the all the files in the same folder, we get the following output

Copy to Clipboard

Accessing a variable or a function from another file in Node JS:

Since ES5 JavaScript did not support modularity, Node JS adopted common js modularity and used the keyword required to access something that is exported from another file.

example:

001.js

Copy to Clipboard

002.js

Copy to Clipboard

In the previous example, we exported only a function from the 001.js file, so we can access only that function in the other file. If we want to export multiple files, we can do it like this

001.js

Copy to Clipboard

002.js

Copy to Clipboard

Another way to exporting multiple files is by creating an Object containing all the variables that we want to export as key value pairs and exporting that object using module.exports syntax.

Accessing a Variable or a Function from another file using ES6+ JavaScript:

JavaScript supports modularity from ES6 and it is very powerful and widely used in many frameworks such as Angular, React JS and also widely used by the developer community even in Vanilla JavaScript applications.

We can export anything that we want to use in another module by using export keyword in ES6+ JavaScript, then we can import it from another file by using the import keyword.

001.js

Copy to Clipboard

002.js

Copy to Clipboard

If you try to run the code, you may get the error “Cannot use import statement outside a module“. That is because, we cannot use the modularity in ES6+ JavaScript directly in the browser or Node JS. If you are trying to run it using Node JS and got the error, make sure that you provided type option to package.json file and give the value module to it. For more info, check Working with ES6 Modules in Node JS

If you get the error in the browser, check How to Work with ES6 Modules in the Browser