BBaysinger
BBaysinger

Reputation: 6987

How to import jQuery into a jQuery plugin in Angular 2+ / Webpack / Angular CLI

I'm trying to import a jQuery plugin into a single Angular component. It runs in every other browser, but IE 11 chokes on it:

SCRIPT1002: Syntax error
main.bundle.js (1376,1)

When I click the error, it shows me the line at issue:

eval("Object.defineProperty(__webpack_exports__, \"__esModule\", { value: true });\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(\"../../../../jquery/dist/jquery.js\");\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__angular_core__ = __webpack_require__(\"../../../core/esm5/core.js\");\n// require('jquery');\n\n\n\n/*\ndjaodjin-annotate.js...

That's not all of it, but it appears to be to do with importing jQuery, and indeed, when I remove the jQuery import, it runs fine.

The issue may be that I'm importing jQuery into a JavaScript (.js) file, which is a jQuery plugin. Here's a simplified version of it:

import * as jQuery from 'jquery';

(function($) {
  'use strict';

  function Annotate(el, options) {
    this.init();
  }
  Annotate.prototype = {
    init: function() {
      console.log('It\'s working.');
    },
  };
  $.fn['annotate'] = function() {

    const annotate = new Annotate($(this));

    return annotate;
  };
})(jQuery);

If I can't import jQuery into a jQuery plugin, how can I use a jQuery plugin? Is there a way around this?

BTW, I'm using jQuery only in one component. The rest of the application is clean of it.

Upvotes: 0

Views: 160

Answers (2)

BBaysinger
BBaysinger

Reputation: 6987

I actually found that my jQuery plugin had errors in it. It had a couple of lines with ES6 syntax that IE didn't like. But when Webpack compiles it, it turns the whole thing into a string, all on one line. At runtime, it then runs eval() on the string. So you don't get valuable error messages with line numbers. It just gives you the stupid error that I got. But I think @David has a good point. We maybe don't need to import jQuery.

Upvotes: 0

David
David

Reputation: 34425

I'd say you don't need to import jQuery in your plugin; your plugin should just assume that jquery has been included and fail if it has not

You can include jquery (first) then your plugin file into your project. Then in your component just declare jquery

declare let $ : any;

and instantiate your plugin like

$('div').annotate();

Upvotes: 1

Related Questions