When trying to load jQuery into a SharePoint Framework project I am running into this error:

Module ''jquery'' resolves to a non-module entity and cannot be imported using this construct

I followed the spfx docs to set it up.

Here are the steps I take after creating a brand new project using the yo generator:

  1. npm install --save @types/jquery
  2. Add "jquery": "https://code.jquery.com/jquery-3.1.0.min.js" to the config file so it now looks like this

    { "entries": [ { "entry": "./lib/webparts/helloWorld/HelloWorldWebPart.js", "manifest": "./src/webparts/helloWorld/HelloWorldWebPart.manifest.json", "outputPath": "./dist/hello-world.bundle.js" } ], "externals": { "jquery": "https://code.jquery.com/jquery-3.1.0.min.js" }, "localizedResources": { "helloWorldStrings": "webparts/helloWorld/loc/{locale}.js" } }

  3. When I add import * as $ from 'jquery'; I get the error above. gulp serve fails as well.

jQuery Error

有帮助吗?

解决方案

There is an issue with @types/jquery version 3.2 and 3.2.1

If you change the version of @types/jquery to 2.0.47 everything works as expected.

Steps I took:

  1. npm uninstall @types/jquery
  2. Update package.json dependency: "@types/jquery": "2.0.47"
  3. npm install

其他提示

You need to add as below :

"externals": {
    "jquery": {
      "path": "https://code.jquery.com/jquery-3.1.0.min.js",
      "globalName": "jQuery"
    }    
},

In order to define an external script as a non-AMD script you need to specify the name of the global variable to which the script will be attached using the globalName property

Reference - Building SharePoint Framework Client Side Web Parts using jQuery

Also, ensure that the jquery entry is present in the tsconfig.json file(found in the root of the solution folder) as below, if not add it:

"types": [
      "webpack-env",
      "jquery"
    ]

So, your full entry would be somewhat as:

{
  "compilerOptions": {
    "target": "es5",
    "forceConsistentCasingInFileNames": true,
    "module": "commonjs",
    "jsx": "react",
    "declaration": true,
    "sourceMap": true,
    "types": [
      "es6-promise",
      "es6-collections",
      "webpack-env",
      "jquery"
    ]
  }
}
许可以下: CC-BY-SA归因
scroll top