【问题标题】:"Cannot invoke an expression whose type lacks a call signature" when importing jQuery in TypeScript在 TypeScript 中导入 jQuery 时,“无法调用类型缺少调用签名的表达式”
【发布时间】:2018-11-27 07:08:22
【问题描述】:

我目前正在评估 TypeScript,但在尝试导入 jQuery 时遇到了一些问题。

import * as $ from 'jquery';
const $el = $('#app');

报告如下错误:

src/log.ts:2:13 - error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '{ default: JQueryStatic; ajaxSettings: AjaxSettings<any>; A
nimation: AnimationStatic; Callbacks: CallbacksStatic; cssHooks: CSSHooks; cssNumber: PlainObject<boolean>; Deferred: DeferredStatic; ... 62 more ...; when<TR1,
 UR1, VR1, TJ1 = any, UJ1 = any, VJ1 = any>(deferredT: TR1 | ... 1 more ... | Thenable<...>, defer...' has no compatible call signatures.

2 const $el = $('#app');
              ~~~~~~~~~

  src/log.ts:1:1
    1 import * as $ from 'jquery';
      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default impo
rt or import require here instead.

我已经安装了jQuery模块如下:

npm i jquery --save
npm i @types/jquery --save-dev

并使用以下生成的tsconfig.json 文件:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true
  }
}

我正在使用以下版本:

{
  "name": "example",
  "version": "1.0.0",
  "description": "example",
  "devDependencies": {
    "@types/jquery": "3.3.22",
    "typescript": "3.1.6",
  },
  "dependencies": {
    "jquery": "3.3.1"
  }
}

我错过了什么?

【问题讨论】:

  • 你不能调用模块命名空间对象
  • @AluanHaddad 你能详细说明一下吗?
  • 这将解释它以及解释您收到的答案的问题。 stackoverflow.com/a/47007576/1915893

标签: jquery typescript


【解决方案1】:

由于@types/jquery 使用export =,因此导入它需要使用import =

改变

import * as $ from 'jquery';

import $ = require('jquery');

【讨论】:

  • 我不知道这个import $ = require('jquery'); 语法。您能解释一下这种语法的来源或记录在哪里吗?
  • 这是特定于 TypeScript 的语法。 typescriptlang.org/docs/handbook/…
  • 就我而言,我还需要将 tsconfig.json 中的模块声明更改为 "module": "commonjs"
  • 如何使用 esnext 模块导入 jquery?
【解决方案2】:

对于“模块”:“esnext”,下面可能会有所帮助,

import jQuery from "jquery";
window.$ = window.jQuery = jQuery;

【讨论】:

    猜你喜欢
    • 2017-09-01
    • 2021-02-06
    • 1970-01-01
    • 1970-01-01
    • 2019-09-28
    • 2019-09-10
    • 2018-12-25
    • 2019-03-01
    相关资源
    最近更新 更多