Search code examples
javascriptnpmecmascript-5

Using npm with vanilla js


Due to the governance constraints on my day-job project, I'm unable to use a lot of the nice new JS libraries and frameworks. So, for the MVP we're using vanilla JS loaded directly (non-minified) to the client (gross). While this is a great way to show management that's not the best approach, I still have to get it out of the door. However, we do have NPM and Node installed on our dev machines, and I'd like to use this to optimize our JS into a combined bundle, with a hash to break caching.

My question is how do I go about gathering a bunch of disjoint JS files and adding them to a new NPM project to be minified while avoiding having the expected variables, objects, and functions being mangled by webpack/prettify?

I tried just copying the js files into the src directory, and adding the normal import/export lines, but I was getting a bunch of "identifier not found" messages in the console, so I think a lot of stuff was getting mangled.

I have some experience using create-react-app for React side projects, but unfortunately that insulates me from the pain of getting a project setup the hard way, and now I'm paying for my inexperience.

EDIT: To be more succinct, I'm trying to package a bunch of existing js files into a single bundle, while maintaining the same interface. If this isn't possible, please let me know. Otherwise, a place to start would be ideal.


Solution

  • In the days before browserify, babel, webpack, grunt, gulp... we would just concatenate the files and minify them. Since the files expose their API as global objects everything keeps working as if the files where included with different script tags.

    On Linux you can simply do this

    cat a.js b.js c.js | uglifyjs -cm > bundle.js
    

    The files would often start with a semicolon to make sure nothing breaks when concatenating them.

    Once babel is configured integration is as easy as

    cat a.js b.js c.js | babel | uglifyjs -cm > bundle.js
    

    https://babeljs.io/docs/usage/cli/