DEV Community

Nikhil Chandra Roy
Nikhil Chandra Roy

Posted on

JavaScript import export module features Tutorials

Hello guys,
In this post, we will learn javascript import, export module features shortly.

1st test.

we will create below files

  • index.html
  • main.js
  • alert.js

so, in index.html we will do like this,

<!doctype html>
<html lang="en">
  <head>
    <title>Title</title>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  </head>
  <body>

    <script src="main.js" type="module"></script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

for script has type attribute where the script get it by module.

In main.js file we will do

import {Alert} from './alert.js';
function Main(){
    Alert()
}
Main()
Enter fullscreen mode Exit fullscreen mode

and in alert.js file

export function Alert(){
    alert("I am alert")
}

Enter fullscreen mode Exit fullscreen mode

so when we reload the page we will see that our module alert.js working with alert("I am alert")
now, we will do some example import,export way for practice and doing.

In alert.js when we don't use default along with function we have to remove the curly bracket in main.js
like

In alert.js

export default function Alert(){
    alert("I am alert")
}
Enter fullscreen mode Exit fullscreen mode

In main.js

import Alert from './alert.js';
Enter fullscreen mode Exit fullscreen mode

and without default, we have to

In alert.js

export function Alert(){
    alert("I am alert")
}
Enter fullscreen mode Exit fullscreen mode

In main.js

import {Alert } from './alert.js';
Enter fullscreen mode Exit fullscreen mode

for multiple function we may use "as" along with function like

import {Alert as nikhil}  from './alert.js';

Enter fullscreen mode Exit fullscreen mode

we can also use variable as well as function for module like below

In alert.js

export let time = new Date().toLocaleTimeString();

Enter fullscreen mode Exit fullscreen mode

In main.js

import {Alert as nikhil, time}  from './alert.js';
function Main(){
    nikhil()
    console.log(time)
}
Main()


Enter fullscreen mode Exit fullscreen mode

This is our short tutorials to use the module in javascript,
I will continue to post for short time to learn small and small things.
If you like this small post, don't forget to comment your opinion.
Thanks.

Top comments (2)

Collapse
 
chandragie profile image
chandragie

Thanks for this short, straight forward but so useful info!

Collapse
 
nikhilroy2 profile image
Nikhil Chandra Roy

welcome,