capaj / require-globify

transform for browserify, which allows to require files with globbing expressions
MIT License
70 stars 11 forks source link

example for custom `resolve` functions #30

Open rafegoldberg opened 7 years ago

rafegoldberg commented 7 years ago

would love to see some better documentation on using a custom resolve function. the docs have a pretty good primer, but an example might help the less intuitive among us. (read: “me”).

ps: loving the built in resolutions– quick and easy to set up, and they've covered most use-cases I've come across till now!

call-a3 commented 7 years ago

An example could be the following:

Say you wanted a resolver that would camelcase all matching files.

main.js could contain the following code:

const includes = require('./includes/*.js', { mode: 'hash', resolve: ['reduce-prefix', 'strip-ext', function my_camelcase_resolver(base, files, config) {
    function camelize(str) { // camelize taken from http://stackoverflow.com/a/2970667
      return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function(letter, index) {
        return index == 0 ? letter.toLowerCase() : letter.toUpperCase();
      }).replace(/\s+/g, '');
    }
    return Object.keys(files).reduce(function(resolved_files, file) {
        resolved_files[camelize(file)] = files[file];
        return resolved_files;
    }, {});
}] });

Which would get converted into

const includes = {
    "oneInclude": require("./includes/one-include.js"),
    "anotherInclude": require("./includes/another-include.js"),
};

Writing this down, I realized this is maybe not the most user-friendly way to do this, especially if you want to use the same resolver multiple times. Also, since it's been a long time since I've worked on this plugin, I might be mistaken about the way to go about this. I suggest you try it out and let me know how it works out. I have several ideas of how this use-case might be improved upon.

rafegoldberg commented 7 years ago

Woah, would not have gotten that! I ended up getting pretty damn good results from the built-in resolvers... Still, great to see an example of how this works. Anyways, appreciate the response; a simplified/streamlined interface for implementing custom resolvers would make this package the jams. I'd be more than happy to help if/where I can be useful.