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 : 8011  
 
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

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…

Awesome JavaScript Games and Js Software to create Games

Best sites js13kGames 2019 - Highlights from the js13kGames 2019 competition. js13kGames 2018 - 13 Games in ≤ 13kB of JavaScript. js13kGames 2017 - Build a game in 13kB or less with js13kGames. Adventure Triangle:…

Is JavaScript good for machine learning?

One of the things you always hear when you are talking to someone related to the M.L. world is that, one must learn Python because the vast majority of the…

First steps into JavaScript – a practical guide 3

After we learned the basic ofaccessing DOM elementsandhow to modify them,we are ready for the more exciting parts – handling DOM events. This allows us to make our web way more…

JavaScript: Promises explained with simple real life examples

Handling asynchronous data flows is complex, who hasn't faced codes like this one?: checkWeather('palma de mallorca', (error, weather) => { if (error) throw error; if (weather === 'well') { return checkFlights('palma…

First steps into JavaScript – a practical guide 2

In the previous aticleFirst steps into JavaScript – a practical guidewe covered the basics of the DOM and its relation to us becoming JS literate. Now that we know how…

First steps into JavaScript – a practical guide

For those who are new to web development, surely the amount of new terminology can sometimes be discouraging. But when it comes to learning JS, some of the first new…