Search code examples
javascriptwebpackgoogle-chrome-extensionbrowserifyparceljs

Bundled Webextension doesn't see JQuery


I'm creating a webextension for Chrome, the following code leads to an error:

$(function () {
  $('[data-toggle="popover"]').popover();
  // ...
});

Chrome complains that:

Uncaught TypeError: jquery_1.default(...).popover is not a function

It looks like bootstrap is simply not available. I know that the import order for scripts is important: Chrome extension "$ is not defined" error

So I made sure that bootstrap is included before my code:

"content_scripts": [
    {
        "js": [
            "assets/jquery/dist/jquery.min.js",
            "assets/popper.js/dist/popper.min.js",
            "assets/bootstrap/dist/js/bootstrap.min.js",
            "content/index.js"
        ],
        "css": [
            "assets/css/extra.css",
            "assets/bootstrap/dist/css/bootstrap.min.css"
        ]
    }
],

These script paths are valid.

EDIT:

I'm sorry, I messed up the documentation of this bug. Apparently, it only happens when I use a bundler, such as parcel. I only tested with parcel, but I believe that this problem would occur with any bundling manager, such as webpack or browserify.


Solution

  • When processing the dependencies with a bundler, such as parcel, jQuery is executed in an environment with CommonJS modules.

    In such a setup, jQuery doesn't add itself to the global window object. However, bootstrap expects the $ function and jQuery on window.

    The solution is to add it manually, the following is typescript code. In JS you don't need the cast to any

    import $ from "jquery";
    (<any>window).jQuery=$;
    (<any>window).$=$;
    import "bootstrap";