Module jquery resolves to a non-module entity
-
25-12-2020 - |
Вопрос
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:
npm install --save @types/jquery
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" } }
When I add
import * as $ from 'jquery';
I get the error above.gulp serve
fails as well.
Решение
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:
npm uninstall @types/jquery
- Update
package.json
dependency:"@types/jquery": "2.0.47"
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"
]
}
}