Search code examples
requirejsamdjs-amd

How get access to amd module from next module during define


I have this working code.

define(['https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js'],function(axios) { 
    axios.post('/user');
});

But I want to use axios inside next module r.js

define([
    'https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js',
    'https://example.com/r.js], function(axios) { 
    return r; 
}); 

But axios is undefined.

r.js

var r = function () {
  console.log('worked') // worked
  axios.post('/user'); // axios undefined
}

Is it possible? I have not access to requre.js config :-(


Solution

  • What your code is doing now:

    • you define a module which has two dependencies, axios and r,
    • requirejs starts downloading both file async
    • r is regular script (not amd module) and does not have axios as dependency
    • if r loads first, then you have axios undefined
    • if axios loads first it registers itself as amd module and it is not visible as global, so you have undefined

    First solution for your problem is to rewrite r as amd module and specify axios as its dependency.

    Second solution is to specify axios as r's dependency via shim.