New to JavaScript and am wondering if all JavaScript has to be "deployed" as individual .js files, or if there are ways to bundle/package multiple JS files as a component, like a Java .jar or a .NET .dll.
For instance, if I have a collection of, say, 30 JS files that make up a reusable library of JS objects and functions, is there a way to package these as a single deployable component or am I stuck copying-n-pasting all 30 files into every project where I want to use them?
What's the norm here? Thanks in advance!
2018 update: You can use CommonJS or ES modules and package them with an appropriate tool like Browserify, webpack, Parcel, etc.
JavaScript can't be compiled (before sending it to the client) of course; the closest equivalent is just to minify them, then glue all the files together. For minification, I personally like Google Closure Compiler; as for the gluing, it's pretty easy to do with your command-line tools. For example:
cat script1.js >> all.js
cat script2.js >> all.js
# etc.
If you plan to use all the content of all the files, you could consolidate their contents into a single js file using a text editor. Having 30 separate .js files will slow down a page load since 30 requests have to be made. You can further reduce the file size by using a JavaScript "minifier", such as http://jscompress.com/ or http://www.minifyjavascript.com/.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With