DEV Community

Smitter
Smitter

Posted on • Edited on

Import Javascript modules using import maps( No npm install )🔥

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:



<!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>



Enter fullscreen mode Exit fullscreen mode

As shown above, we are trying to load lodash' startCase functionality into our site. startCase will simply convert string to start case.

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. 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

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 :



{
   "imports": {
     "nameOfImport": "locationOfSourceCode",
     "nameOfSecondImport": "locationOfSourceCode",
   }
}


Enter fullscreen mode Exit fullscreen mode

See snippet below:



<!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>



Enter fullscreen mode Exit fullscreen mode

We already know name of our import to be @lodash/startCase and where to find our library, we chose UNPKG.
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
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

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

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

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

I hope I have helped you learn something new today.
Here is my twitter handle you can follow me to get what am upto these days or just want to say hi👋. I treat strangers nicely😊

Top comments (2)

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

You do not need import maps to import external modules natively, although they are a nice addition. JS has supported native module imports for a good number of years now.

Collapse
 
smitterhane profile image
Smitter

Exactly, I may say the real deal with import maps is that they simplify the long module import path and map it to a short and precise term