简体   繁体   中英

Bundle external javascript libraries automatically

I often see browser-focused javascript libraries with an option to install over npm .

Is there a reason to install it using npm instead of just using <script src="cdn-url"></script> ?

I am loading many libraries, so I guess it might be a good idea to fetch these files, so I don't make so many url requests (even though all the requests are targeting CDNs).

I could potentially install via npm and then use <script src='/node_modules/...'></script> , but then I need to make these paths public accessible using express.static() or something like that.

I know that I could use webpack, browserify, etc., but they seem overly complicated when I just want to bundle a few external libraries into 1 file automatically.

The point of using npm in this case is so you get the updates automatically. You bundle to reduce the number of requests and include only 1 script tag.

but they seem overly complicated when I just want to bundle a few external libraries into 1 file automatically.

This is complicated unfortunately. It would be nice if it wasn't. Also, you need to think about things like browser caching when you update a library. If you have a vendor libraries bundle, you will have to manually cachebust with a query string when you update. So to simplify the process, webpack does it all for you.

I would move to Webpack and use the CommonsChunkPlugin to create a vendor build. See this example.

To fully automate everything, combine this with Html Webpack Plugin to automatically add the script tags and cache-bust with hashing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM