What’s the right way to use webpack-specific functionality in node.js?

webpack defines require.ensure and require.include, which aren’t available in node.js proper. If I want to create modules that use these functions, but still run in node.js, how do I do that? They can certainly just be defined as no-ops in node.js.

3 thoughts on “What’s the right way to use webpack-specific functionality in node.js?

  1. @jhnns I’d like to pre-bundle only for use on the client but I still want to be able to execute the same code (which use require.ensure) in Node.

    My use case is I’m using React UI library and it allows to render UI components on server as well as on the client.

  2. I use this

    let proto = Object.getPrototypeOf(require);
    !proto.hasOwnProperty("ensure") && Object.defineProperties(proto, {
        "ensure": {
            value: function ensure(modules, callback) {
                callback(this);
            },
            writable: false
        },
        "include": {
            value: function include() {},
            writable: false
        }
    });
    

    in global of node

  3. @snadn: Nice one,.. Only problem is webpack is giving a critical dependencies warning for this bit -> var proto = Object.getPrototypeOf(require);
    Although everything seems to work fine.

    @fresheneesz: I did a couple of tests,
    Although not a complete test, I did a simple ->

    var k = 0;var proms = [];console.time('t1');for (var l = 0; l < 10000; l ++) proms.push(new Promise(function (resolve, reject) { k ++; resolve(); }));Promise.all(proms).then(function () { console.timeEnd('t1'); })

    My results,..
    Chrome Browser:
    Bluebird: 377.339ms, Native: 255.331ms
    Node:
    Bluebird: 79.960ms, Native: 38.801ms

    Ah!!, forget that. What I didn’t do in Bluebird was ->
    Promise.config({longStackTraces: false});

    Node Bluebird then gives 9.998ms.. and then Chrome bluebird -> 71.670ms

    So indeed Native promises are embarrassingly slower,.. What gives, doesn’t make any sense..

Comments are closed.