Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically require an aliased module using webpack

Tags:

webpack

I'm configuring a bunch of module aliases through webpack via resolve.alias. Then, in my app code, I would like to require one of these modules using a variable that contains an alias name:

var module = require(moduleAlias);

Unfortunately, this creates a "context module" containing everything in the script's directory and its descendants which isn't what I was after in this particular case. Also, since nowhere in my code am I explicitly requiring all the aliased modules, they don't get built into my app.

Two questions:

  1. How do I make sure all aliased modules are bundled with my code?
  2. How do I access them using a variable that contains an alias?

Thanks!

like image 977
Aaronius Avatar asked May 05 '15 23:05

Aaronius


1 Answers

This only answers the second part of your question: if you have bundled module with alias and you want those aliases to be requirable from a context:

To my knowledge, there is no official way of doing it with webpack. I created a plugin, working with Node 4 (you can adapt if you want to use pure ES5), that will add to any context the list of aliases:

'use strict';

class AddToContextPlugin {
  constructor(extras) {
    this.extras = extras || [];
  }

  apply(compiler) {
    compiler.plugin('context-module-factory', (cmf) => {
      cmf.plugin('after-resolve', (result, callback) => {
        this.newContext = true;
        return callback(null, result);
      });

      // this method is called for every path in the ctx
      // we just add our extras the first call
      cmf.plugin('alternatives', (result, callback) => {
        if (this.newContext) {
          this.newContext = false;

          const extras = this.extras.map((ext) => {
            return {
              context: result[0].context,
              request: ext
            };
          });

          result.push.apply(result, extras);
        }
        return callback(null, result);
      });
    });
  }
}

module.exports = AddToContextPlugin;

This is how you can use it:

webpack({
      /*...*/
      resolve: {
        alias: {
          'alias1': 'absolute-path-to-rsc1',
          'alias2$': 'absolute-path-to-rsc2'
        }
      },
      plugins: [
        new AddToContextPlugin(['alias1', 'alias2'])
      ]
    })

And it result as the following code generated:

function(module, exports, __webpack_require__) {

    var map = {
        "./path/to/a/rsc": 2,
        "./path/to/a/rsc.js": 2,
        "./path/to/another/rsc.js": 301,
        "./path/to/another/rsc.js": 301,
        "alias1": 80,
        "alias2": 677
    };
    function webpackContext(req) {
        return __webpack_require__(webpackContextResolve(req));
    };
    function webpackContextResolve(req) {
        return map[req] || (function() { throw new Error("Cannot find module '" + req + "'.") }());
    };
    webpackContext.keys = function webpackContextKeys() {
        return Object.keys(map);
    };
    webpackContext.resolve = webpackContextResolve;
    module.exports = webpackContext;
    webpackContext.id = 1;

}
like image 130
JBE Avatar answered Oct 17 '22 21:10

JBE