Home > Mobile >  How to bundle npm packages for vanilla JavaScript frontend development and production builds on CDN
How to bundle npm packages for vanilla JavaScript frontend development and production builds on CDN

Time:12-27

I have a vanilla HTML/CSS/JavaScript site (repository) which uses ES6 modules. It can be successfully deployed to GitHub pages and Netlify.

In my HTML, I import main.js like this:

<script src="js/main.js" type="module" defer></script>

In my main.js file, I import other modules I have made like this:

import * as data from './data.js';
import displayUserCard from './displayUserCard.js';

Now I want to also install and import npm modules to use on my site just as I use my own code on my site.

I install lodash like this:

npm i lodash

Then in my main.js file, I import lodash like this, just as I do in my Node apps:

import _ from 'lodash';

This of course doesn't work and gives me the following error, since we are now in the browser and not in a Node app:

^Uncaught TypeError: Failed to resolve module specifier "lodash". Relative references must start with either "/", "./", or "../".^

Researching this, I understand that such a development environment needs a web bundler, but I find everything from dated tools such as Browserify and RequireJS, to over-complex tools such as WebPack, to newer bundlers such as Parcel, Vite and Snowpack which all don't seem to address this problem of easily bundling npm packages for both development and production builds.

What is the most straight-forward way in 2021/2022 to use node modules such as lodash in vanilla HTML/CSS/JavaScript frontend apps so that they can be bundled, built and deployed at CDNs like GitHub pages, Netlify and Vercel?

CodePudding user response:

What you need to do is install a javascript bundler that translates and stores all the needed modules(e.g lodash) in an accessible place for your browser to find.

Watch this video, its straight to the point and sums up everything.

  • Related