“This is the 22nd day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

How do I reference the ESM in a browser?

Hello, I’m Shanyue. Bundless became increasingly popular, especially due to the introduction of Vite.

ESM is the foundation of Bundless, and it is essential to know about IT. In this article, I will give you a brief overview of how to reference ESM in your browser.

Native Import: Import from URL

Native ESM can be used directly in a browser with script[type=module].

This also makes front-end Bundless possible.

<script type="module">
  import lodash from 'https://cdn.skypack.dev/lodash'
</script>
Copy the code

Since the front end runs in the browser, it can only import the Package from the URL

  1. Absolute path:https://cdn.sykpack.dev/lodash
  2. Relative path:./lib.js

Now open the browser console and paste the following code into the console. Thanks to the introduction of HTTP import, you’ll find it much easier to debug the LoDash column library.

> lodash = await import('https://cdn.skypack.dev/lodash')

> lodash.get({ a: 3 }, 'a')
Copy the code

ImportMap

However, Http imports require you to enter a full URL each time, which can be quite inconvenient compared to the old bare Import specifiers, as shown in the following example:

import lodash from 'lodash'
Copy the code

Unlike Node.js, which can rely on the system file system, it layers down to node_modules

/home/app/packages/project-a/node_modules/lodash/index.js
/home/app/packages/node_modules/lodash/index.js
/home/app/node_modules/lodash/index.js
/home/node_modules/lodash/index.js
Copy the code

In ESM, raw imports can be made to work by importMap:

<script type="importmap">
{
  "imports": {
    "lodash": "https://cdn.skypack.dev/lodash"."ms": "https://cdn.skypack.dev/ms"}}</script>
Copy the code

You can import modules in the same way as before

import lodash from 'lodash'

import("lodash").then(_= >...).Copy the code

So how do you import child paths through bare imports?

<script type="importmap">
{
  "imports": {
    "lodash": "https://cdn.skypack.dev/lodash"."lodash/": "https://cdn.skypack.dev/lodash/"}}</script>
<script type="module">
import get from 'lodash/get.js'
</script>
Copy the code

Import Assertion

With script[type=module], you can import not only Javascript resources, but also JSON/CSS, as shown in the following example

Not exactly ESM, since it’s not even ES, let alone ECMAScript Module.

<script type="module">
import data from './data.json' assert { type: 'json' }

console.log(data)
</script>
Copy the code