Last active
January 18, 2019 11:31
-
-
Save ecommpro/362649f2f61c7de5ca18f751e649a35a to your computer and use it in GitHub Desktop.
Webpack resolver plugin that implements "priority to nearest directory" at resolving references inside modules.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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