2

I need to use jquery in my webpart function, remote jquery lib added from cdn;

SPComponentLoader.loadCss('https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js');

and this is my simple line throws exception;

private postMessage(e): void {
        $("#myDiv").show()

this is the error gulp tool throw;

[13:48:46] Error - typescript - src\webparts\contact\components\Contact.tsx(134,9): error TS2304: Cannot find name '$'.
    [13:48:46] Error - 'typescript' sub task errored after 1.44 s
     "TypeScript error(s) occurred."

Is there any external react package for jquery ? how can I use jquery in spfx webpart?

9

You are trying to load javascript library as css. That's not correct.
What you can do is to include jquery as your dependency under config and the use it inside web part.
Here are the steps:

  1. Under config/config.json, externals section add below code:

"jquery": {
      "path": "https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js",
      "globalName": "jQuery"
}
  1. Add jquery type definitions by running npm install --save @types/jquery
  2. Import jquery variable into your web part : import * as $ from 'jquery';
  3. Use $ in your code.
3

SPComponentLoader.loadCss is to load css

Approach 1: You need install the typings of jquery as below:

tsd install jquery --save

After that in your config.json, add the below entry in the externals sections:

"jquery": "https://code.jquery.com/jquery-3.1.0.min.js"

After that, in your webpart you need to import jQuery

import * as $ from 'jquery';

After that, you can use your code :

$("#myDiv").show()

Reference - Using external library in SPFx

Approach 2

In your webpart, add the below code:

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

After that, in the class, inside your render method, you can use below code:

  SPComponentLoader.loadScript('https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js', { globalExportsName: 'jQuery' }).then((jQuery: any): void => {
    this.jQuery = jQuery;        
  });

Reference - SPComponentLoader.loadScript

  • tsd install jquery --save not worked some reason, even cant ping "192.30.253.117" this is the server ip address. here it looks in console;"[ERR!] Error: connect ETIMEDOUT 192.30.253.117:443" – TyForHelpDude Jan 30 '17 at 11:29
  • hmm, you need to do this first npm install tsd -g. After that run the tsd install jquery --save command ! Also @Sergei answer is correct as well ! – Gautam Sheth Jan 30 '17 at 11:31
  • hi, can you check this post? sharepoint.stackexchange.com/questions/206441/… – TyForHelpDude Jan 30 '17 at 19:40

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.