Import One Js File Into Another in The Plain Js

by Luigi Nori Date: 16-04-2020 javascript es6 es2015 include import export


Until some years ago, it was not possible to import one js file or block of code from one file into another but since 2015, ES6 has introduced useful 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.

The static import statement is used to import bindings which are exported by another module. Imported modules are in strict mode whether you declare them as such or not. The import statement cannot be used in embedded scripts unless such script has a type="module".

There is also a function-like dynamic import(), which does not require scripts of type="module".

Backward compatibility can be ensured using attribute nomodule on the script tag.

How we include the js files:

index.html

<!DOCTYPE html>
<html>
    <head>

    </head>
    <body>
        <script type="module" src="script2.js"></script>
    </body>
</html> 

script1.js

export default function Hello() {
    return "Hello buddy!";
}

script2.js

import { Hello } from './script1.js';
let val = Hello;
console.log(val);

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

Code and Syntax Explanation of the code above:

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 (line number 1 in script1.js). In script2.js, we imported that module by writing the following code/syntax :

import { Hello } from './script1.js';

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

export let Name = (name) => {return "My name is " + name;}
export let Address = (address) => {return "i live in " + address;}
export let Age = (age) => {return "my age is "+ age;}

script2.js

import { Name, Address, Age} from './script1.js';
let val = Name("John");
let age = Age(26);
console.log(val + " and " + age);

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.

import { Name, Address, Age} from './script1.js';

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:

Infact there are two types of exports:

  1. Named Exports (Zero or more exports per module)
  2. Default Exports (One per module)

This is only a quick explanation, you can fond more examples at MDN web docs:
Import Statement Reference at MDN
Export Statement Reference at MDN

 
by Luigi Nori Date: 16-04-2020 javascript es6 es2015 include import export hits : 14646  
 
Luigi Nori

Luigi Nori

He has been working on the Internet since 1994 (practically a mummy), specializing in Web technologies makes his customers happy by juggling large scale and high availability applications, php and js frameworks, web design, data exchange, security, e-commerce, database and server administration, ethical hacking. He happily lives with @salvietta150x40, in his (little) free time he tries to tame a little wild dwarf with a passion for stars.

 
 
 

Related Posts

Validating HTML forms using BULMA and vanilla JavaScript

Today we are going to write about contact forms and how to validate them using JavaScript. The contact form seems to be one of the top features of every basic home…

A FULFILLED PROMISE - Using the FETCH API to make AJAX calls

In this article we talked about what AJAX calls are and how to use them in a traditional way, by using the XMLHttpRequest (XHR) object. In short, thanks to AJAX…

How to use Parallax.js effect on your website

Today, we're going to write about the parallax effect, similar to parallax scrolling, and how to implement it to improve your landing page. In webdev, they say mobile first -…

How to make the website's dark mode persistent with Local Storage, CSS and JS

Recently we wrote about how to do a switchable alternative color mode or theme, a very useful and popular feature to websites. Today’s article is going to be about how…

Dark Mode on website using CSS and JavaScript

In today’s article we are going to learn how to build pretty much standard these days on the web pages and that is the alternative color mode and switching between…

JavaScript: Spread and Rest operators

In today’s article we are going to talk about one of the features of the ES6 version(ECMAScript 2015) of JavaScript which is Spread operator as well as Rest operator. These features…

Javascript: what are callbacks and how to use them.

Today we are going to learn about a concept that is widely used in javascript and that is used quite a lot by today's frameworks, libraries, especially NodeJS. This is…

HTTP Cookies: how they work and how to use them

Today we are going to write about the way to store data in a browser, why websites use cookies and how they work in detail. Continue reading to find out how…

The package managers npm and yarn: main differences

Npm and yarn are package managers that help to manage a project’s dependencies. A dependency is, as it sounds, something that a project depends on, a piece of code that…

The Javascript asign() method to merge and clone objects

In this article, we will be covering Object.assign()method in javascript in detail with examples. A javascript object is a collection of key-value pairs. Keys are also known as properties of object. Keys…

All the javascript functions and methods to manipulate arrays

This article will show that the prominent JavaScript array functions are .map(), .filter(), and .reduce(), and will then go through examples of instances in which .every() and .some() would save…

TypeScript: The evolution of JavaScript

When you're involved in the development of a large project, programming languages like JavaScript don't seem to be the best solution. Their lack of elements such as Language Aids has…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration