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

3
  • prntscr.com/iblrdv so there's something wrong with your jquery Commented Feb 7, 2018 at 22:03
  • is jquery the path of your JQuery Library?? you have to type the path of your JQuery library Commented Feb 7, 2018 at 22:03
  • stackoverflow.com/questions/28969861/… Commented Feb 7, 2018 at 22:06

2 Answers 2

9

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
Sign up to request clarification or add additional context in comments.

1 Comment

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.
-1

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';

1 Comment

No -- he is having a runtime error. Type declarations don't affect runtime code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.