Import Javascript modules using import maps( No npm install )🔥
Tags: webdev, javascript, programming, html
Published: 2022-07-08 21:43:00

### How it's normally done
External(_third party_) libraries can add complexity to a new Javascript project in order to introduce newer functionality  that does not need to be written from scratch.
To be able to install and use these external code libraries, you will need a build tool _such as webpack_, that can parse the code and bundle the libraries that you import into a final format.
After this build setup, you can add and integrate new code functionality with ease. **But by default, most build tools will bundle all the code into one larger file adding even external code that most users of the library may not need**. The user will load the code regardless of whether they will need to execute it. These build tools are flexible that they can be configured **to load code only as required**. But doing this is quite some work.

### Did you know?
We have a spec called **import maps** that will allow you to:
- Import third party(_external_) libraries
- Download the source only when it is needed

Are you afraid you may be digging into something deep? **Actually no. It's completely no brainer.**

Import maps won't replace build tools completely that perform many other functions like minifying code and building stylesheets. Import maps will allow you to get your application up and running quickly **using only the native browser functionality**(_No build tool_).

### How to use import maps
Let's see this in action. We first create a folder called `import-maps` and change into our new directory. Then we create a file called `index.html` at the root of the folder we are inside. Add markup as shown below to our `index.html` file as shown below:

```html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Import maps</title>
  </head>
  <body>
    <script type="module">
      import startCase from "@lodash/startCase";

      const elem = document.createElement("h2");
      elem.textContent = "import maps demystified";

      document.body.appendChild(elem);
    </script>
  </body>
</html>

```
As shown above, we are trying to load lodash' `startCase` functionality into our site. `startCase` will simply convert string to [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).

**Just a note:** I have added an attribute `type="module"` to our script tag to allow splitting of code and enable use of import and export statements.

Open this file(`index.html`) in your browser to see the output. If you are using vs code, you can serve the `index.html` file using [Live server extension](https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer). Alternatively, if you have Nodejs installed on your system, simply run `npx serve` at the root of your project.

When we open our browser to view our results, we get a blank screen. Open browser dev tools and click on the console tab, we see an error as shown below:
![browser console error](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nr6m8yg76lbjefzp39xo.png)

As we may have expected the error to occur, the browser does not know where to find the lodash library. It is expecting that we are loading the library from our web server on a path  relative to the current file and that we may have failed to include relative path specifiers. _That is either "/", "./", or "../"_.

To fix this, we use **import maps** to tell the browser where to find external code.
An **import map** is a Javascript object where the key is the name of the import, in our case it will be `@lodash/startCase`.
Basically structure of an import map is :
```javascript
{
   "imports": {
     "nameOfImport": "locationOfSourceCode",
     "nameOfSecondImport": "locationOfSourceCode",
   }
}
```
See snippet below:
```html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Import maps</title>
  </head>
  <body>
    <script type="importmap">
      {
        "imports": {
          "@lodash/startCase": "https://unpkg.com/lodash-es@4.17.21/startCase.js"
        }
      }
    </script>
    <script type="module">
      import startCase from "@lodash/startCase";

      const elem = document.createElement("h2");

      // capitalize the first letter of every word
      elem.textContent = startCase("import maps demystified");

      document.body.appendChild(elem);
    </script>
  </body>
</html>

```

We already know name of our import to be `@lodash/startCase` and where to find our library, we chose [UNPKG](https://unpkg.com/).
**UNPKG** is a content delivery network(CDN) for any package you can find at `npm`. Therefore if you can `npm install` a package, you should also be able to load it via UNPKG.

Lodash library that supports **es imports** is found at the folder `lodash-es`, which is the case in our project. Note the `lodash-es` in our url to load the library from UNPKG, i.e `"https://unpkg.com/lodash-es@4.17.21/startCase.js"`. Loading from `lodash` folder will not work as it uses **commonjs modules**.
Refresh your browser and **voila! Things should work!**

![Successful import map run](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ktpotsif6h8r5j4b6ilb.png)
You can see every word has been capitalized which is a functionality provided by lodash.
Congrats! We have succeesfully loaded an external library without a build tool and without running `npm install`. It's simple, right?

## What's happening?
Open the browser dev tools and switch to the network tab.
After opening the network tab, refresh the page and you'll see that the browser is loading code dynamically. Whenever it finds a new import statement, it imports the relevant code.

More importantly, notice that all of the code is loaded lazily. That means that the browser does not import any code until it is specifically needed.

![Network tab of browser console](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w7qus5nswf7vgqmanqpq.png)

For example even though `"https://unpkg.com/lodash-es@4.17.21/startCase.js"` is in the `<script type="importmap">`, the browser would not load it since it is  never imported into code. **The import map is a map of locations, and does not import any code by itself**

You may note other modules are also loaded from Lodash UNPKG source in network panel. These are the dependencies of the `"https://unpkg.com/lodash-es@4.17.21/startCase.js"` file from UNPKG which are imported into it.

**Quick tip💡:** You can view the file `"https://unpkg.com/lodash-es@4.17.21/startCase.js"` by simply adding `browse` in the URL of the source of the external library as illustrated below:

![unpkg browse option](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o6aftakfquz7jgiksjm3.png)

**My final note:** Import maps are not yet widely supported. The good news is that most modern browsers support this module functionality. You can check for browser support [here](https://caniuse.com/import-maps)

You may want to play with the code to find out your own discoveries. You can find the repository of what we have done  [here](https://github.com/hane-smitter/import-maps)

I hope I have helped you learn something new today.
Here is my [twitter handle](https://twitter.com/smitterhane) you can follow me to get what am upto these days or just want to say hi👋. I treat strangers nicely😊