Chris Nevill
Chris Nevill

Reputation: 6152

Importing global JS File with SystemJS and JQuery Dependancy

For testing purposes only I'm trying to import the following javascript file from Zurb Foundation using SystemJS

http://foundation.zurb.com/sites/docs/assets/js/docs.js This script requires JQuery.

My config.js file contains the following:

meta: {
    "zurbDocs": {
      "scriptLoad": true,
      "format": "global",
      "exports": "zurbDocs",
      "deps": [
        "jquery"
      ]
    }
  },

map: {
...
    "jquery": "npm:[email protected]",
    "zurbDocs": "http://foundation.zurb.com/sites/docs/assets/js/docs.js",
...

I then attempt to do an import

import 'zurbDocs';

However an error is thrown:

Uncaught ReferenceError: $ is not defined(…)

This comes from within the doc.js file when it goes to use jQuery's $ symbol at line 3215 - $('[data-docs-code]').each(function(index, value) { What am I doing wrong?

Upvotes: 1

Views: 137

Answers (1)

artem
artem

Reputation: 51609

Unfortunately it seems that "scriptLoad": true has very limited compatibility with deps.

The way SystemJS normally works is to fetch a module, discover its dependencies (by scanning the source for import statements or require calls), then fetch its dependencies and so on, then "link" modules, which involves executing them in correct order determined by their dependencies.

The assumption here is that the order in which modules are fetched is not affected by their dependencies.

This assumption breaks when scriptLoad is true, because when you use <script> tag it's not possible to fetch global module, but not execute it.

You can do a very simple test with one global script a.js depending on another one b.js, if you watch network traffic you will see that systemjs is always fetching a before b, regardless of any configuration settings.

This does not matter if the global module does not try to use its dependencies immediately, but creates some global variables or functions that you can call later to do the work - everything would be resolved by the time you call the functions provided by the module.

Unfortunately this is not true for zurb docs, which tries to do something using jQuery immediately when you load it with <script> tag.

Upvotes: 1

Related Questions