How to bundle npm packages for vanilla JavaScript frontend development and production builds on CDN servers?
Asked Answered
P

1

5

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?

Pyrotechnics answered 25/12, 2021 at 13:0 Comment(0)
S
6

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.

Scavenger answered 25/12, 2021 at 13:8 Comment(3)
ok, I was familiar this this Fireship video but watching again, 0:55 I already agree, "bundling HTML, CSS and JavaScript is truly the most annoying aspect of building a web application"Pyrotechnics
Yap, but the benefits far outweigh the inconvenienceScavenger
That Fireship video turned out to be the best no-nonsense introductory to using Webpack that I know and was exactly what I needed to get me past my hang up expressed in this question, thanks. I built a project based on for anyone struggling with the same issue here: onespace.netlify.app/howtos?id=475Pyrotechnics

© 2022 - 2024 — McMap. All rights reserved.