JavaScript Modules is now supporting in all major browsers.
Let's see how it works.
for demo purpose, I created an index.html and math .mjs, script.mjs.
you can create .js extension its, not a problem but use a .mjs extension for the consistency to know what are the modules and what are the scripts?.
math.mjs file
function add(n1,n2){ | |
return n1+n2; | |
} | |
function sub(n1, n2) { | |
return n1 - n2; | |
} | |
export {add,sub}; |
in above code, I created two functions and exported it.
Now, these functions are available to import.
script.mjs file
import {add,sub} from './math.mjs'; | |
let s =add(1,2); | |
let diff = sub(2,1); | |
document.querySelector('.add').innerHTML = 'Addition of (1,2) is '+s; | |
document.querySelector('.diff').innerHTML = 'Subtraction of (2,1) is ' + diff; | |
At final we are creating the HTML file with our modules.
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
<link rel="stylesheet" href="styles.css"> | |
<title>Document</title> | |
</head> | |
<body> | |
<div class="add"></div> | |
<div class="diff"></div> | |
<script type="module" src="./script.mjs"></script> | |
<script nomodule src="./fallback.js"></script> | |
</body> | |
</html> |
we need to specify the type in script tag for the modules mime type is the module.so that browser treated it as a module rather than normal script.
in above code 15th line I used to tell the browser it is not a module and if the modules are not supported in browsers please use this fallback.js.
final output is
Hope you guys love these.
Top comments (1)
Apparently since Firefox 60 you have modules: developer.mozilla.org/en-US/Firefo...
Maybe you can test it...