【问题标题】:I get "TypeError: $ is not a function" when using "import * as jQuery"使用“import * as jQuery”时出现“TypeError: $ is not a function”
【发布时间】:2020-08-25 19:00:37
【问题描述】:

我有以下 JavaScript,执行时没有任何错误或警告:

import * as jQuery from './node_modules/jquery/dist/jquery.min.js';
window.$ = jQuery;

...但是当我尝试使用我的新$() 函数...

$(document).ready(function() {
    console.log('Hello!');
} );

...我收到此错误:

TypeError: $ is not a function

我做错了什么?

【问题讨论】:

    标签: javascript jquery npm javascript-import


    【解决方案1】:

    使用类型的方法(首选)

    最好的方法是使用 jQuery 类型:

    1. 安装 jQuery

      npm install --save jquery
      
    2. 安装类型定义

      npm install -D @types/jquery
      
    3. 并按如下方式导入

      import * as $ from 'jquery';
      

      Demo


    快速和基本的方法

    而不是做

    window.$ = jQuery;
    

    一起去

    declare var $:any;
    

    【讨论】:

    • 感谢您的回答,Zain!这给了我TypeError: Error resolving module specifier: jquery
    • 我已经添加了演示的链接,你可以检查一下,我可以用第二种方法运行它
    • 是的,它似乎在您的演示中运行良好——谢谢。出于某种原因,当我在本地运行它时它不起作用。奇怪。
    • 你是否也安装了依赖和@types/jquery?你能在codesandbox.io上创建一个最小的例子,我可以帮你调试吗?
    • 哈哈——我以前从未使用过codeandbox,看起来学习曲线相当陡峭,因为我什至无法让他们的“vanilla JS”模板在浏览器面板中显示文本. codesandbox.io/s/recursing-cloud-3njzd?file=/src/index.js(编辑:它适用于 Chrome,但不适用于 Firefox。我会继续修改。)
    【解决方案2】:

    听起来你正在这样做:

    import * as $ from 'jquery;
    

    应该是这样的:

    import $ from 'jquery';
    

    也去

    declare var$: any; 
    

    而不是

    window.$ = jQuery;
    

    【讨论】:

      猜你喜欢
      • 2014-03-14
      • 2017-08-01
      • 2016-07-07
      • 1970-01-01
      • 1970-01-01
      • 2021-04-26
      • 2015-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多