2

I am new to SPFx and I am getting an error while trying to add jQuery and external JS in SPFX.

Example my web-part name is FlipBookWebPart and I am trying to add turn.js and modernizr.js into the FlipBookWebPart.ts.

I have declared the modernizr in config.json like:

enter image description here

And below is an error that I received when add the web-part in local-workbench.

enter image description here

In the webpart.ts, I add jQuery and modernizr using following code

 import * as jQuery from "jquery";
 import "jqueryui";
 require('modernizr');
2

Try following steps:

  1. Run npm i modernizr and then npm i @types/modernizr --save-dev.
  2. Then add its reference to config.json in externals{} like:
    "externals": {
        "modernizr": {
          "path": "node_modules/modernizr/src/modernizr.js",
          "globalName": "modernizr"
        }
     }
  1. Then reference the file in your WebPart.ts file like:
    import * as modernizr from 'modernizr';

Reference:

Use existing JavaScript libraries in SharePoint Framework client-side web parts.

| improve this answer | |
  • Thanks.. I will check on that – crysis08 Jan 17 at 12:12
0

It seems like modernizr script from the CDN does not contain any modules. Try to use SPComponentLoader.

import { SPComponentLoader } from '@microsoft/sp-loader';

Inside your render() or onInit() method (onInit() is more preferable, because it runs only once):

SPComponentLoader.loadScript('https://code.jquery.com/jquery-2.2.4.min.js', {
    globalExportsName: 'jQuery'
}).then(($: any) => {
    $(function() {
        console.log('jQuery is loaded');
    });
    SPComponentLoader.loadScript('https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.js', {
        globalExportsName: 'Modernizr'
    }).then((Modernizr: any) => {
        if (Modernizr.touchevents) {
            console.log('touch');
        } else {
            console.log('no touch');
        }
    });
});

Or you can just use modernizr without loading jQuery.

Also, some info on adding non-module scripts.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.