Skip to content

Instantly share code, notes, and snippets.

@thepont
Created October 3, 2018 02:00
Show Gist options
  • Save thepont/03d1af7806dc909c214e1d0422fb1594 to your computer and use it in GitHub Desktop.
Save thepont/03d1af7806dc909c214e1d0422fb1594 to your computer and use it in GitHub Desktop.
Way of loading local modules while using yarn pnp for module loading.
var Module = require('module').Module;
var path = require('path');
var fs = require('fs');
require('./.pnp.js');
const pnpLoad = Module._load;
function fileExists(path){
try {
fs.statSync(path);
return true;
} catch(ee) {
return false;
}
}
Module._load = function(request, parent, isMain){
try {
return pnpLoad(request, parent, isMain);
} catch (ee) {
let modulePath = path.resolve('./dist', request, 'index.js');
if(! (fileExists(modulePath = path.resolve('./dist', request)) || fileExists(modulePath = path.resolve('./dist', request + '.js')) || fileExists(modulePath = path.resolve('./dist', request, 'index.js')))){
throw ee;
}
let module = new Module(modulePath, parent);
Module._cache[modulePath] = module;
if (isMain) {
process.mainModule = module;
module.id = '.';
}
try {
module.load(modulePath);
} catch(ee) {
delete Module._cache[modulePath];
}
return module.exports;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment