Now Reading
JavaScript import maps at the moment are supported cross-browser

JavaScript import maps at the moment are supported cross-browser

2023-05-03 05:54:32

ES modules are a contemporary solution to embody and reuse JavaScript code in net purposes. They’re supported by fashionable browsers and supply a number of advantages over older, non-modular approaches to JavaScript improvement.

A contemporary method to make use of ES modules is with the &LTscript kind="importmap"> tag. This tag means that you can outline a mapping of exterior module names to their corresponding URLs, which makes it simpler to incorporate and use exterior modules in your code.

To make use of the &LTscript kind="importmap"> strategy, you first want so as to add it to the &LThead> part of your HTML doc. Contained in the tag, you possibly can outline a JSON object that maps module names to their corresponding URLs. For instance:

script kind="importmap">
{
"imports": {
"browser-fs-access": "https://unpkg.com/browser-fs-access@0.33.0/dist/index.fashionable.js"
}
}
&LT/script>

This code defines a single exterior module named "browser-fs-access" and maps it to the URL of the browser-fs-access library, hosted on the unpkg CDN. With this mapping in place, now you can use the import key phrase to incorporate the browser-fs-access library in your code. Word that the import key phrase is just obtainable inside a script tag with the kind="module" attribute.

button>Choose a textual content file&LT/button>
script kind="module">
import {fileOpen} from 'browser-fs-access';

const button = doc.querySelector('button');
button.addEventListener('click on', async () => {
const file = await fileOpen({
mimeTypes: ['text/plain'],
});
console.log(await file.textual content());
});

&LT/script>

Utilizing the &LTscript kind="importmap"> tag and the import key phrase gives a number of advantages over older, non-modular approaches to JavaScript improvement. It means that you can clearly and explicitly specify the exterior modules your code is determined by, which makes it simpler to grasp and keep your code. Total, utilizing ES modules with the &LTscript kind="importmap"> tag is a contemporary and highly effective solution to embody and reuse JavaScript code in net purposes. You’ll be able to feature-detect help as follows:

if (HTMLScriptElement.helps('importmap')) {
// The importmap characteristic is supported.
}

Browser help

  • Chrome 89, Supported 89
  • Firefox 108, Supported 108
  • Edge 89, Supported 89
  • Safari 16.4, Supported 16.4

Additional studying #

Acknowledgements #

Hero picture by CHUTTERSNAP on Unsplash.

Source Link

What's Your Reaction?
Excited
0
Happy
0
In Love
0
Not Sure
0
Silly
0
View Comments (0)

Leave a Reply

Your email address will not be published.

2022 Blinking Robots.
WordPress by Doejo

Scroll To Top