【问题标题】:Uncaught (in promise) TypeError: $ is not a functionUncaught (in promise) TypeError: $ is not a function
【发布时间】:2023-04-18 02:26:01
【问题描述】:

我正在尝试使用 Material Design lite 显示带有波纹的按钮,但出现以下错误:

app.js:3 Uncaught (in promise) TypeError: $ is not a function(...)

html 文件:

  <body>
      <script>
System.paths['jquery'] = './node_modules/jquery/dist/jquery.js';
              System.import('src/app.js');
</script> 
  </body>

app.js:

      import $ from 'jquery';
import {Button} from './ui/button.js';
let b=new Button('click me');
b.appendToElement($('body'));

button.js:

      import {BaseElement} from './base-element.js';

export class Button extends BaseElement {

    constructor(title) {
        super();
        this.title = title;
}

    getElementString() {
        return `
            <button class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent"
                style="">
                ${this.title}
            </button>
        `;
    }

}

base-element.js:

    import $ from 'jquery';

export class BaseElement {

    constructor() {
        this.element = null;  // jQuery object
    }

    appendToElement(el) {
        this.createElement();
        el.append(this.element);
}

    createElement() {
        let s = this.getElementString();
        this.element = $(s);
    }

    getElementString() {
        throw 'Please override getElementString() in BaseElement';
    }
}

【问题讨论】:

  • 它描述了你的 jquery 没有被导入到你的文件中
  • @SanjayPatel 是我的语法错误还是其他错误?
  • console.log($) 得到什么?
  • @Gothdo 同样的错误
  • 试试import 'jquery'?

标签: javascript jquery ecmascript-6 material-design traceur


【解决方案1】:

当 jQuery 将自己附加到全局对象时,您应该使用 import 'jquery'

在全局对象上使用import $ from 'jquery'阴影$,默认导出为'jquery',但jQuery不导出任何东西,所以$ === undefined

【讨论】: