Search code examples
javascriptsystemjsjspm

systemjs variable from another file


I have two javascript files in my project. One (index.js) declares the Material object and the other (nav.js) adds a method to Material.

I am using SystemJS to import both of these into my HTML page.

When the page loads I am getting an error from the second file saying that Material is undefined.

If I am loading the first file before the second as so:

<script src="./jspm_packages/system.js"></script>
<script src="./config.js"></script>
<script>
    System.import("./scripts/index.js");
    System.import("./scripts/nav.js");
</script>

shouldn't the Material object already be defined?


Here are my two files:

index.js:

var $ = require('jquery');

// Define Material
var Material = {
  components: {},
  reload: function () {
    console.log('reloading...');
  },
  dev: true
};

and nav.js:

var $ = require('jquery');

Material.initHeader = function () {
  console.log('initializing header...');
};

Here is the error I am getting

Uncaught ReferenceError: Material is not defined at nav.js:3

Any help?


Solution

  • Modules are self-contained. They do not modify the global namespace as they are loaded. If you want some stuff from another module, you have to import it:

    var $ = require('jquery');
    var ix = require('./index.js');
    
    ix.Material.initHeader = function () {
      console.log('initializing header...');
    };