Lazy loading modules in Nodejs

My first question is, who is responsible for handling statements require

in a Nodejs application? is it Node itself? or CommonJS? or RequireJS? Is CommonJS included with Node? how about RequireJS?

Now my second question is:

I have an if-else statement that decides if we are rendering server side or client side. I want to load various libraries when rendering client side or server side. Can modules be loaded at runtime? exactly at the moment when it is required?

    if (typeof window === undefined){
       var serverSideLibrary = require('A');
       //.... 
    }else{
       var clientSideLibrary = require('B');
    }

      

It looks like Node is downloading everything it needs before launching the application. So it doesn't matter if you require it at the top of your code or in this if-else block.

+3


source to share


3 answers


In Node.js, Node handles the require

. And you are wrong. require

is not evaluated until the evaluation of the program achieves it. If you have this code:

var mod;

setInterval(function() {
  if (true) {
    mod = require("a");
  } else {
    mod = require("b");
  }
}, 5000);

      

... you can be sure of two things: 1. The module b

will never be loaded, and 2. The module a

will not be loaded until after five seconds.



It require

is only defined in the browser if you are using a library that defines it, such as RequireJS, Browserify, or Webpack. In general, these tools remain close to the behavior of Node: while the browser can load all of the code at once (especially if you have a build step that puts all your modules in one file), they will wrap each module in so that it doesn't actually get evaluated until until require

d.

If you want to load different modules depending on whether your code is running on the client or server, I would recommend doing this in your build tools, most of which have been built, such as those mentioned above, have this functionality, or are available as a plugin. not just the operator if

, because with the operator if

you are still making the browser load code that it will never use.

+6


source


Override the file extension .js

to hide files .js

from the default directory loop when called require

, and create your own methods that programmatically require an on-demand request:

var fs = require('fs'),
    IonicAppLib = module.exports,
    path = require('path');

var camelCase = function camelCase(input) {
    return input.toLowerCase().replace(/-(.)/g, function(match, group1) {
        return group1.toUpperCase();
    });
};

//
// Setup all modules as lazy-loaded getters.
//
fs.readdirSync(path.join(__dirname, 'lib')).forEach(function (file) {
  file = file.replace('.js', '');
  var command;

  if (file.indexOf('-') > 0) {
    // console.log('file', file);
    command = camelCase(file);
  } else {
    command = file;
  }

  IonicAppLib.__defineGetter__(command, function () {
    return require('./lib/' + file);
  });
});

IonicAppLib.__defineGetter__('semver', function () {
  return require('semver');
});

      

which wraps the accessor for the variable assigned to the call require

:



var IonicAppLib = require('ionic-app-lib');

      

Links

0


source


Remember nodeJs is interpreted. So it just does everything inside the code so that it doesn't depend on what it is! ... It doesn't matter where you fulfill your "requirement (something)", it will be executed fine, and no error should be thrown out if you don't have sintax or have the required library installed.

So you can do what you want! You can require packages inside If statements. What you should consider is that you are following the correct path after this, because if you try to use a library that has never been imported, you will get a RunTime error.

Hooray!

-2


source







All Articles