0

I've recently started to use RequireJS, which enables me to organize my code in a nice way. So, define and require became my best friends. But now I see one problem, which I do not know how to solve in terms of RequireJS, or in terms of some particular Design Pattern. So, imagine, I have a really huge module containing zillions of methods. I define it like so:

define(function(BIG_MODULE){
    return {
        property_0: "value_0",
        property_1: "value_1",
        ....
        property_zillion: "value_zillion",
        method_0: function(){...},
        ...
        method_zillion: function(){...}
    }
});

Please, do not ask me, why I have such a huge module - it's just an abstraction. And, so, the question now is - if it is possible to import or require not the entire module, but some of its properties and methods? Lets say I somehow assigned my module to some local instance and if I investigate the internals of this instance, then I can see, that it contains only some particular properties and methods. Is it possible?

Jacobian
  • 10,122
  • 29
  • 128
  • 221
  • `Please, do not ask me, why I have such a huge module - it's just an abstraction.` In terms of [tag:design-patterns] the problem you're having is one of modularity. RequireJS wants to load modules. If you can, try to redesign your huge module (a.k.a. GodClass) into smaller ones. It's not easy, but it's a classic problem: See more at http://stackoverflow.com/questions/14870377/how-do-you-refactor-a-god-class – Fuhrmanator Sep 28 '15 at 15:40
  • Thanks! I have forgotten about notorious GodClasses. – Jacobian Sep 28 '15 at 19:10

1 Answers1

1

One thing you definitely should do is not export anything that is not meant to be part of the public API of your module.

This being said, RequireJS has no notion of importing only part of a module. When you list a module as a dependency, RequireJS loads the module, loads and executes its dependencies, calls its factory function (this is the function passed to define) with the resolved dependencies, and records what the module exported. Then when you use it somewhere else, the module's export value is bound to the corresponding parameter in the callback. So in this code

require(["foo"], function (foo) {...

you get as foo all of what was exported by the module "foo".

If you use ES6 (aka ES2015) and have the ES6 modules converted to AMD modules (by Babel, for instance), then you can have some language-based notion of a partial import. For instance, if foo exports like this return { bar: 1, baz: 2, bwip: 3 } then you could import only bar like this:

import { bar } from "foo";

console.log(bar);

This would output 1 to the console. Note, however, that this does not change how the module is loaded and processed by RequireJS. RequireJS reads the whole module and executes all of the factory function. The import above only affects how the code that loads "foo" gets to access the exported values.

Louis
  • 146,715
  • 28
  • 274
  • 320