代码之家  ›  专栏  ›  技术社区  ›  Anish

Typescript和Jquery导入-$不是函数

  •  2
  • Anish  · 技术社区  · 7 年前

    我在jquery中使用typescript,但我一直

    未捕获类型错误:$不是函数

    以前有人见过这个吗?

    我正在将typescript编译到ES2017,然后使用webpack传输到ES5。

    //tsconfig
    {
          "compileOnSave": true,
          "compilerOptions": {
            "module": "es2015",
    
            "removeComments": true,
            "preserveConstEnums": true,
            "sourceMap": true,
            "target": "es2017",
            "noImplicitAny": false,
            "outDir": "Output",
            "esModuleInterop": true
    
          }
        }
    

    如何使用jquery

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

    浏览器会看到jquery($) enter image description here

    但我明白了

    enter image description here

    2 回复  |  直到 7 年前
        1
  •  7
  •   Anish    6 年前

    找到了解决方案。要使用$作为函数,我必须从jquery npm模块导入默认值。有了这个import语句,它就可以工作了。

    import $ from "jquery";
    

    我还必须在tsconfig中打开此功能。json

    "allowSyntheticDefaultImports":  true
    
        2
  •  0
  •   davidkonrad    7 年前

    似乎缺少typescript编译器所需的jQuery类型定义。您需要同时安装jQuery和jQuery类型定义。如果您正在使用 npm 要安装软件包,请执行以下步骤。(否则,请确保在您的环境中安装了这两个软件包)

    1、安装jQUery

    npm install --save jquery
    

    2、安装jQuery类型定义

    npm install -D @types/jquery
    

    现在,您可以在代码中导入jQuery,如下所示

    import * as $ from 'jquery';