access module of other context in requirejs

236 Views Asked by At

I am trying to access a togetherJS (https://togetherjs.com/docs/contributing.html) module from an external requireJS app. It seems impossible.

TogetherJSConfig_noAutoStart = true;
var CJS = CJS || {};

CJS.require = require.config({
    paths: {
        togetherjs: 'https://togetherjs.com/togetherjs-min',
        cjs: 'scripts/c'
    }
});

CJS.require(['togetherjs'], function() {
 // not working
 peers = require({context: "togetherjs"})("peers");

 // not working
 // Module name "peers" has not been loaded yet for context: togetherjs. Use require([])
  TogetherJS.require = require.config(TogetherJS.requireConfig);
  TogetherJS.require("peers");
});

If I do not use requireJS in my app, I can access the module I want:

  // works if I do not use requireJS in my app. 
  var peers = TogetherJS.require('peers').getAllPeers();

Is it possible, and if so, how? I could not find any information anywhere.

Thanks

1

There are 1 best solutions below

0
On

I'm not entirely sure of what you are trying to accomplish here. It looks like you are mixing up require.js asynchronous api with node.js synchronous require api.

I think that when you do require.config without specifying a context name, you are configuring the global require context. So calling CJS.require(..) should be equivalent to calling window.require(..).

The line

peers = require({context: "togetherjs"})("peers");

looks strange to me. Usually you would specify the context name in the require.config call and the first parameter to a require(..) call would be the dependency list. Also, you would normally pass a callback function to the require(..) call as well.

I hope those pointers can help you (or others) get better acquainted with require.js