Using npm packages in the frontend without any bundlers

Published:
Updated:

It’s possible to use npm packages on your frontend without any bundlers today.

This is amazing because we don’t need to create complicated workflows to reuse code — we can simply retrieve the library from npm. This makes our projects simpler, more straightforward, and more welcoming for newcomers in our industry!

In this article I’m going to show you two ways to include npm packages without any bundlers. They are:

  1. Import the library from a CDN
  2. Serve up your node_modules folder

Prerequisites

You can only use these methods if the library you’re using uses ES Modules (ESM).

The methods I’m mentioning here do not work with Common JS modules.

Method 1: Import the packgae from a CDN

When authors push their library onto npm, CDNs like JSDelivr and unpkg updates their servers with the latest version of these libraries immediately.

We can import these libraries in our JavaScript file. When you do this, you want to specify the version number — so the CDN can deliver the right version every time.

Here’s an example where I import zlFetch.

import zlFetch from 'https://cdn.jsdelivr.net/npm/[email protected]/src/index.js'

Importing libraries directly from CDNs can be unwieldy especially if you need to import the same library in many files.

A good workaround is to import all the libraries you need into a lib.js file. This will be your central place to manage dependencies.

You can then export the libraries and import them from elsewhere.

// lib.js
export const zlFetch = (
  await import('https://cdn.jsdelivr.net/npm/[email protected]/src/index.js')
).default
// fileOne.js
import { zlFetch } from './lib.js'
// fileTwo.js
import { zlFetch } from './lib.js'

Method 2: Serve it up from your node_modules folder

This can only be done if your server lets you serve up the node_modules folder.

Let’s assume you have this project structure.

- project
  |- index.html
  |- js
    |- main.js
  |- node_modules

If your server can serve the node_modules folder, importing the library is easy — you simply traverse into the node_modulesfolder and grab the correct javascript file.

import zlFetch from '../node_modules/zl-fetch/src/index.js'

http-server is an example of a server that lets you serve up the node_modules folder. You can this method working by running the serer.

npx http-server

Sadly, you won’t be able to use this method if you use Express because Express doesn’t expose the node_modules folder.

That’s it!

Here's how to become great at JavaScript in less than 2 months

If you’re stuck because of your lack of JavaScript skills, you can stop worrying now.

We’ll help you become amazing at JavaScript — we have a course that can help you understand and use JavaScript easily.

And we’re going to give you three chapters for free because we love to help developers become superheroes.

Just click the button below to become an amazing JavaScript developer.