2

I'm using typescript with jquery, but I keep getting

Uncaught TypeError: $ is not a function

Has anybody seen this before?

I'm compiling typescript to ES2017, then transpiling to ES5 using webpack.

//tsconfig
{
      "compileOnSave": true,
      "compilerOptions": {
        "module": "es2015",

        "removeComments": true,
        "preserveConstEnums": true,
        "sourceMap": true,
        "target": "es2017",
        "noImplicitAny": false,
        "outDir": "Output",
        "esModuleInterop": true

      }
    }

How jquery is being used

import * as $ from "jquery";
 var form = $(document.createElement('form'));

The browser sees jquery ($) enter image description here

But then I get this

enter image description here

Anish
  • 2,633
  • 3
  • 23
  • 27

2 Answers2

6

Found the solution. To use $ as a function, I had to import the default from the the jquery npm module. With this import statement, it works.

import $ from "jquery";

I also had to turn this on in tsconfig.json

"allowSyntheticDefaultImports":  true
Anish
  • 2,633
  • 3
  • 23
  • 27
  • With this approach I get the `Uncaught SyntaxError: The requested module '../lib/jquery/dist/jquery.js' does not provide an export named 'default'` * But I did not install jquery via `npm`, that might be the reason. – Muflix Oct 25 '20 at 10:08
0

Seems like you are missing jQuery type definitions which are needed by typescript compiler. You need to install both jQuery and jQuery type definitions. If you are using npm to install packages, the below steps will work. (Otherwise make sure you have both the packages installed in your environment)

1.Install jQUery

npm install --save jquery

2.Install jQuery type definitions

npm install -D @types/jquery

Now, you can import jQuery in your code as below

import * as $ from 'jquery';
Pradeep Kumar
  • 995
  • 5
  • 7