简体   繁体   中英

What is RequireJS shim exports for?

I'm reading through Backbone Fundamentals and am currently on the section that describes how to build an app with RequireJS.

From what I understand, the idea behind shimming is that normally when you require modules, RequireJS figures out how to load their dependencies as well. But when you're trying to load a non-AMD module, this doesn't work (I don't know why, but that's a separate question). To get around this, you could set up a shim to say, "load X before Y".

require.config({
  shim: {
    'Y': ['X']
  }
});

I see that you could use exports to say, "put this non-AMD thing into a global variable instead of a module".

require.config({
  shim: {
    'Y': {
      exports: 'globalY'
    }
  }
});

Um, what problem does that solve? Isn't the problem with non-AMD libraries just that RequireJS can't figure out the dependencies?

The "I don't know why" part actually needs to be addressed to answer the question. Shimming is only required for non-AMD modules, and loading a non-AMD module via RequireJS doesn't work precisely because RequireJS requires AMD modules. That is, it needs the module to be wrapped in a define call that contains a list of dependencies and a factory method ( more details here ). "Standard", old-style libraries write their stuff into the global scope, into an arbitrarily named namespace (in Backbone's case: window.Backbone ). Historically, the devs would write a tiny wrapper module to convert "old" library into AMD, eg:

backbone-wrapper.js

define([], function() {
  return window.Backbone;
});

Adding shim configuration ( added in RequireJS 2.0 ) allowed dealing with this declaratively in the configuration.

Shimming is not saying "put this non-AMD thing into a global variable instead of a module" . Shimming is saying "load this non-AMD library and expose the global namespace specified in the exports variable as if it was an AMD module".


It's actually nicely explained in RequireJS's documentation and some other SO questions: 1 , 2 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM