divinelemon
divinelemon

Reputation: 2097

Bundle and publish client-side web code on NPM

I made a Javascript file. Let's say the contents of it are this:

let myCoolAlert = (str) => {
    alert(str)
}

// in a different js file (SO doesn't allow you to cross-file as far as I know
myCoolAlert('Hello World!')

I already hosted the JS file on a CDN. Now, I want it to be automatically hosted locally by whoever installed it if you install it via NPM. Is there a way to do this?

Also, I noticed that to do the same using Socket.io, you have to pass Socket.io to the HTTP/HTTPS server you created. Will I have to do this also? (I would prefer not).

Thanks!

Edit:

I am trying to make a better alert system (like sweetalert). I coded it in Javascript and works when using it through the CDN. However, I also want users to be able to install this via NPM (kind of like SweetAlert? I am not sure about that last statement however because I do not use it). When they install it with NPM, it's obviously going to be useless because it is for the browser. However, I want them to either:

  1. Automatically have the source code needed available at a URL like localhost:3000(or server name)/betterAlert.js and be able to use that URL as a script in the HTML files
  2. OR, have the user pass the HTTP or HTTPS server they created to the module (like socket.io does) and have it automatically host it from there.

Please note:

The code I am trying to bundle is native to the web. Will it still work with a bundler like webpack?

Is this possible? Thanks again.

Upvotes: 0

Views: 746

Answers (1)

Zac Anger
Zac Anger

Reputation: 7767

To bundle client-side code and publish it through NPM you'll need to do a couple things: learn how to package and publish modules, and write some code that can be consumed. This means using module.exports or export to expose your library, depending on whether you want to use CJS or ESM. The consumer of your library can usually be assumed to be using Webpack, Fuse, Rollup, or some other bundler which knows how to deal with modules.

You can also use a tool like Rollup yourself to build and bundle up your library for different targets and apply various transformations to it (example from my own library boilerplate). Using a bundler like this makes more and more sense as your library inevitably grows larger.

Using modules like this rather than distributing through a CDN or in some other way that puts your library code on the global/window object is generally better for consumption in complex apps, large apps, and/or apps already being built with tools like Webpack (so, anything written in React, Angular, Vue, etc.). But having a CDN distribution is still a good idea for something like your library, since it may well be used by people building sites with jQuery and vanilla JS.

Upvotes: 1

Related Questions