javascriptjqueryecmascript-6material-designtraceur

Uncaught (in promise) TypeError: $ is not a function


I am trying to display a button with ripple using material design lite but getting the following error:

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

html file:

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

Solution

  • As jQuery attaches itself to the global object you should use import 'jquery'.

    Using import $ from 'jquery' shadows $ on the global object with the default export of 'jquery', but jQuery doesn't export anything, so $ === undefined.