Search code examples
javascriptecmascript-6browserifybabeljs

How can I make use of global variables in ES2015 modules


I am using Gulp, Babelify and Browserify to compile ES2015 into ES5.

Folder structure:

project
  - js
    - level.js
    - main.js

If I have the below defined module:

// level.js
var level = [];

level[0] = {
    name: 'level1',
    grid: {
        width: GRID_WIDTH,
        height: GRID_HEIGHT
    }
};

export default level;

And then I have my main JavaScript file:

// main.js
import level from './level.js';

var siteGame = (function() {
    var GRID_WIDTH = 50,
        GRID_HEIGHT = 50;

    console.log(level);

}());

How can I make sure that GRID_WIDTH and GRID_HEIGHT are available inside level.js?

At the moment I get an error, advising that GRID_WIDTH is undefined (from level.js)


Solution

  • The whole point of modules is that each has their own scope. If you want to "inject" data into a module, either export a function from level.js that accepts the dimensions, constructs the array/object and returns it, or put the dimensions in their own module and import it in level.js