thorstorm
thorstorm

Reputation: 153

RequireJS not loading module before use its variables

I'm getting an undefined error from a new library I just plugged in to requireJS. I know the undefined error is related with the 'wNumb' module not loading before is used. If I load 'wNumb' module in config.js like this: require(['main', 'wNumb']); everything works.

// conifg.js
require.config({
  paths: {
    'main': 'main',
    'socketio': './libs/socket.io/socket.io',
    'plotly': './libs/plotly/plotly-latest.min',
    'renderDataToPlotly': './scripts/renderDataToPlotly',
    'noUISlider': './libs/noUiSlider.8.5.1/nouislider.min',
    'wNumb': './libs/wnumb-1.0.2/wNumb',
    'sliders': './scripts/sliders',
    'makePlotlyWindowResponsive': './scripts/makePlotlyWindowResponsive'
  }
});

require(['main']);

// main.js
define([
  'socketio',
  'sliders', //---------------------------------------------> NOTE: sliders.js loading here
  'makePlotlyWindowResponsive',
  'renderDataToPlotly'
  ],
  function(io, sliders, makePlotlyWindowResponsive, renderDataToPlotly) {
    //
  }
);

// sliders.js
define(['noUISlider', 'wNumb'], function(noUISlider, wNumb) {
  console.log(wNumb); // ---------------------------------------------------> undefined
});

Question: Why is this happening? Should not 'wNumb'have been loaded by the time console.log(wNumb); executes?

Thank you

Upvotes: 0

Views: 583

Answers (2)

Louis
Louis

Reputation: 151401

Indeed, when you have trouble with a library you are using with RequireJS, you should check how it exports itself. The documentation will sometimes tell you what it is compatible with. Otherwise, you have to read the source code. To use wNumb 1.0.2 with RequireJS have have it behave mostly like a proper AMD module you must use a shim:

shim: {
    wNumb: {
        exports: "wNumb",
    },
}

This will give to the module the value of the global variable wNumb (which is the same as window.wNumb). This is how you get libraries that don't know anything about AMD but export themselves in the global space to work with RequireJS.

However, if you can upgrade wNumb to 1.0.4 that would be better because this version has introduced the proper code to make wNumb a proper AMD module: it calls define when it detects that there is an AMD loader available. You don't need a shim then.

Upvotes: 1

thorstorm
thorstorm

Reputation: 153

I found out what was going on inside the 'wNumb' module. I read 'wNumb' code and saw at the end of the file this: enter image description here

Apparently, 'wNumb' was being exported to the window object. When I use window.wNumb (1, on the image) inside sliders.js, it returns the expected function (2, on the image). As a proof: enter image description here

Upvotes: 0

Related Questions