简体   繁体   中英

Load external libraries from CDN with angular-cli

I would like to use the angular-cli to build an app that bundles my app code but does not include the Angular2 framework or other large external JavaScript libraries in the bundled code. I would like to load these libraries from a CDN when the page loads. Is there a way to do this?

Also, is there a way to do this while preserving the benefits of a local build where only the parts of the Angular2 framework that I am using gets loaded?

I saw this question, but it was for SystemJS and I don't think it applies to Angular-cli: How to load angular2 using CDN and SystemJS

You simply need to add the appropriate <script src=""> tags pointing to the CDN to the index.html file. Remember to remove the .js files from angular-cli.json so they don't get bundled with the app.

Currently, you can't do that for the Angular 2 js files itself, they are automatically bundled with your app. Though the latest updates enable the web servers and browsers to cache the vendor files, so they don't get redownloaded on every visist to your app but only when the hash changes.

When creating an application with Angular, version 2 or greater, uses a build system that only includes the portions of the Angular platform you use. Templates can be compiled at build time, allowing the build process to remove the template compiler from your bundled payload. Finally the build process does tree-shaking with the help of static analysis of your code, which further removes from the payload bundle unused portions of the platform.

If you provide Angular from a CDN, it would need to be the kitchen sink, the entire platform. This would be huge and a detriment to your application.

You are much better off allowing angular-cli bundle the portions of the platform that you need. As the WebPack treeshaking plugin improves your bundle sizes will get smaller.

I would add your whole app to a CDN such as Akamai . For example (depending on how your app is structured) you could cache files such as the ones in the below list...

  • index.html
  • List item
  • application.css
  • application.js
  • templates.js
  • vendors.css
  • vendors.js

This would give even better performance than just caching the Angular framework files on the CDN.

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