0

I am trying to build a web app based on the new React template in ASP.NET Core 2.0

I want to make an ajax request via jQuery. My issue is that the template by default uses TypeScript (tsx) files and if I try to do something along the lines of

import { $ } from 'jquery'

I get a TypeScript error, that says it cannot determine type for $.

Following this answer https://stackoverflow.com/a/32052431/8991878, I went ahead and did an npm install --save-dev @types/jquery.

The first error went away, but now I get

Module "jquery: has no exported member $.

Another post I found suggested removing the curly brackets {}. After doing that I instead got

Module "jquery" has no default export

I am a back-end developer and I do not have lots of experience with both TypeScript and jQuery so I guess I am just doing something dumb incorrectly.

I read about TypeScript's module resolution here https://www.typescriptlang.org/docs/handbook/module-resolution.html and I did verify that my package.json file has "@types/jquery": "^3.2.16". I also have jquery in both node_modules and node_modules/@types

Hentov
  • 473
  • 1
  • 4
  • 12

2 Answers2

1

I believe the correct style of import for jQuery is the simplest form:

import 'jquery';

If you are doing this with the native browser loader, it would need a file extension at the moment, so the plain browser version would be:

import './jquery.js';

(This is with the actual jQuery file being copied to root, so the browser doesn't have to navigate into node_modules.

Fenton
  • 241,084
  • 71
  • 387
  • 401
  • This did resolve the issue. However, now when I try to call $.ajax I get $ is not defined. Any idea about how can I get this fixed? – Hentov Nov 29 '17 at 16:27
  • UPDATE: Well, not sure if it is the best solution, but I did an import * as $ from 'jquery' and it managed to work. – Hentov Nov 29 '17 at 16:30
1

For anyone wondering, solved it by changing import { $ } from 'jquery' to import * as $ from 'jquery'

Hentov
  • 473
  • 1
  • 4
  • 12
  • jQuery does support CommonJS module syntax, but in a browser it sets: `window.jQuery = window.$ = jQuery;` - which is why I wouldn't use an alias when importing jQuery (specifically jQuery... in case anyone reads this and thinks I am talking generally!) – Fenton Nov 30 '17 at 09:42
  • In the future, they will almost certainly gravitate towards ECMAScript modules in the jQuery library. That will change the answer when it happens. – Fenton Nov 30 '17 at 09:43