Javascript Interview #4: How do you import one JS file into another in the plain JS?

Javascript Interview Questions
Share this:

I was asked this question casually in an interview and I really had no idea because once I needed it and I simply included two files in HTML file and ran the script inside script tag in that HTML file. But, I knew this wasn’t the answer so when I went home I was amazed when I found this. I didn’t have energy to look for a better solution so I loosed an opportunity.

Today, I remembered that day of the interview and wrote this article so that my experience should benefit you and save yourself from losing any opportunity.

#Let’s begin the learning

It was not possible to import one js file or block of code from one file into another but since 2015, ES6 has introduced fascinating ES6 modules. With the module standard, we can use import and export keyword and syntax given to include and export the module in JS respectively.

This is a sample code :

HTML (index.js) :

script1.js

script2.js

Run the above sample code blocks in your local system/local server, you will get the console output as:

I am here to help you

Code and Syntax Explanation of everything above:

Here in script1.js, we exported the module with the syntax of :

export module ;

Similarly, in our case, we exported the function Hello by writing the export keyword in the function definition i.e line number 1 in script1.js. In script2.js, we imported that module by writing the following code/syntax :

Right now in script1.js, we have only one module to export but what if we had multiple modules to export? That is also possible with a similar syntax but with a slight modification:

Sample Code for multiple modules:

script1.js

script2.js

Here in script1.js, we have three modules named Name, Address, and Age. In Script2.js, we imported those modules with similar but little different syntax.

Note: we didn’t have { } in earlier import code because that was default export ( remember one file can have only one default export).

When we remove that default keyword in previous code of script1.js, we get an error in the console and that error looks like this:

Goodbye take care and stay safe !!!

Bye, see you again !!!!

1

Related posts

One Thought to “Javascript Interview #4: How do you import one JS file into another in the plain JS?”

  1. Pankaj Shah

    Pretty insightful one!! I solved my problem with slightly different way as type=”module” starts creating a problem of CORS locally. And import did not work in my case. What I did was grabbed webpack package using npm and used it to build and bundled all the js scripts in one place and used that built scripts in my html file. There’s another way too, using require(‘module_name’) but require does not work directly on client side and should download require.js for using it.

Leave a Reply