Loading external packages

If your project requires external libraries, such as jQuery or similar, commonly used libraries, you might consider loading these from CDN. You can always bundle them within your project, but this means that your packages that are deployed will grow in size. Also, maintaining or updating these external libraries quickly becomes time-consuming, as you need to manually track what version of each library is being loaded on a page.

A solution for this is to load these external libraries from a CDN. The process is quite straightforward:

  1. First, install the npm package for your library. In our example, this would be jQuery:
npm install jquery --save
  1. Next, run the npm install to ensure that all packages are updated:
npm i 
  1. Then, open the config/config.json file within your project and look up the externals portion of the file. Update this to reflect that you'll load jQuery from a CDN, with a globalName of jQuery. Your external configuration in the file should look like this:
"externals": {
"jquery": {
"path": "https://code.jquery.com/jquery-2.1.1.min.js",
"globalName": "jQuery"
}
}
  1. Now, open your web part project file and import the following library:
import * as $ from 'jquery';
  1. Finally, use jQuery within your code. A simple test would be an alert in your render() method:
public render(): void {
$(function(){
alert('hi');
});
  1. Run gulp serve to verify that your code compiles and loads up in SharePoint Workbench. You should see an alert when the web part is added on the page:

When you now run gulp bundle -ship, you can verify that jQuery is not packaged as part of your web part--it is referenced externally.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.16.184