DEV Community

Cover image for Js Modules are Now supporting in Browsers
Sai gowtham
Sai gowtham

Posted on

12 3

Js Modules are Now supporting in Browsers

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};
view raw math.mjs hosted with ❤ by GitHub

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;
view raw script.mjs hosted with ❤ by GitHub

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>
view raw index.html hosted with ❤ by GitHub

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.

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (1)

Collapse
 
rhymes profile image
rhymes

currently, Mozilla is not supporting modules.

Apparently since Firefox 60 you have modules: developer.mozilla.org/en-US/Firefo...

Maybe you can test it...

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs