webpack-contrib / bundle-loader

Bundle Loader
MIT License
658 stars 59 forks source link

How do you use it in practice? #18

Closed jeron-diovis closed 6 years ago

jeron-diovis commented 9 years ago

I mean, it changes syntax. It changes default behavior. Async require works and expected to work like this:

require(["./foo.js"], function(fileExports) {
  // use it
});

But now we can't do this. Now we should do some magic:

require(["./foo.js"], function(cb) {
    cb(function(fileExports) {
       // use it
    });
}

Besides it already violates basic principles, webpack documentation says that loaders should be mostly defined in webpack config. Which is reasonable. And when we define our bundles in config, then in code we have no idea about what this module exactly is - and so which syntax must be used to actually load it. Sure, it can have some self-describing name, but it's not a real solution.

Can't understand how to practically use it. Should I really write require("bundle!...") everywhere?

mnpenner commented 8 years ago

I've defined these two functions:

/**
 * Loads an app-script asynchronously.
 *
 * @param {String} filename Asset to load
 * @see https://github.com/webpack/webpack/issues/118#issuecomment-28559053
 * @see https://github.com/webpack/bundle-loader
 */
window.requireAsync = function requireAsync(filename) {
    return new Promise((resolve,reject) => {
        try {
            require('bundle!../app/' + filename)(resolve);
        } catch(err) {
            reject(err);
        }
    });
};

const _ = require('lodash');

window.runScript = function(filename, ...args) {
    return requireAsync(filename).then(module => {
        if(module) {
            if(_.isFunction(module)) {
                return module(...args);
            }
            if(_.isFunction(module.default)) {
                return module.default(...args);
            }
        }
    });
};

And then I use them to run my page-specific scripts:

<script>runScript("app_menu.js",{"app_id":"io","system_type":"ecr"})</script>

This calls the default function I've defined in the bundle and passes in my args. Great way to pass data through to JS.