Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Webpack resolver plugin that implements "priority to nearest directory" at resolving references inside modules.
// ModulesInNearestDirectoryPlugin.js
// by EcommPro SL (https://ecomm.pro)
"use strict";
const forEachBail = require("enhanced-resolve/lib/forEachBail");
module.exports = class ModulesInHierachicDirectoriesPlugin {
constructor(directories = [], overrides = []) {
this.directories = [].concat(directories);
this.overrides = [].concat(overrides);
}
apply(resolver) {
const target = resolver.ensureHook("resolve");
resolver.getHook("module").tapAsync("ModulesInNearestDirectoryPlugin", (request, resolveContext, callback) => {
const fs = resolver.fileSystem
const { context: { issuer = "" } } = request;
const priority = [].concat(this.overrides).concat(this.directories.sort((directory, _) => (issuer.indexOf(directory) ? 1: -1)))
forEachBail(priority, (directory, callback) => {
fs.stat(directory, (err, stat) => {
if(!err && stat && stat.isDirectory()) {
const obj = Object.assign({}, request, {
path: directory,
request: "./" + request.request
});
const message = "looking for modules in " + directory;
return resolver.doResolve(target, obj, message, resolveContext, callback);
}
if(resolveContext.log) resolveContext.log(directory + " doesn't exist or is not a directory");
if(resolveContext.missing) resolveContext.missing.add(directory);
return callback();
});
}, callback);
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.