-->

jspm: Error when importing a jQuery plugin

2019-03-30 11:35发布

问题:

I'm trying to import a jQuery plugin (namely https://github.com/Mottie/Keyboard) using jspm/SystemJS.

At first, I installed the module by simply typing the following command:

jspm install github:mottie/keyboard

I then added the line to import the library in my code, just after importing jQuery:

import keyboard from 'mottie/keyboard';

However, when running the code, I encountered the following error:

Uncaught TypeError: Multiple defines for anonymous module

Googling the error didn't provide me with a solution, at least not one that I could understand... I don't know if there are some jspm gurus around here that could help me? :)

Many thanks in advance...

回答1:

If you look at the source for jQuery.keyboard, it uses a UMD pattern twice in the code:

Once at https://github.com/Mottie/Keyboard/blob/master/js/jquery.keyboard.js#L31, and once at https://github.com/Mottie/Keyboard/blob/master/js/jquery.keyboard.js#L2165.

SystemJS is detecting the file as AMD, but it is defining itself twice instead of once.

Basically as a result this isn't a valid AMD module, so you need to tell SystemJS to treat it as a global instead.

This can be done with an override:

jspm install github:mottie/keyboard -o "{format: 'global'}"

Even then, the above requires that jQuery is already loaded. For this we can add a shim on jQuery to enforce the dependency.

The standard jQuery plugin override with a shim looks like:

override.json

{
  "main": "js/jquery.keyboard.js",
  "shim": {
    "js/jquery.keyboard": {
      "deps": ["jquery"]
    }
  },
  "dependencies": {
    "jquery": "*"
  }
}

We can then install this with:

jspm install github:mottie/keyboard -o override.json

Do post your override to the jspm registry if it works out and then other users can benefit as well.