JavaScript import export module features Tutorials
Nikhil Chandra Roy
Posted on November 17, 2020
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>
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()
and in alert.js file
export function Alert(){
alert("I am alert")
}
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")
}
In main.js
import Alert from './alert.js';
and without default, we have to
In alert.js
export function Alert(){
alert("I am alert")
}
In main.js
import {Alert } from './alert.js';
for multiple function we may use "as" along with function like
import {Alert as nikhil} from './alert.js';
we can also use variable as well as function for module like below
In alert.js
export let time = new Date().toLocaleTimeString();
In main.js
import {Alert as nikhil, time} from './alert.js';
function Main(){
nikhil()
console.log(time)
}
Main()
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.
Posted on November 17, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 16, 2024