Created
October 3, 2018 02:00
-
-
Save thepont/03d1af7806dc909c214e1d0422fb1594 to your computer and use it in GitHub Desktop.
Way of loading local modules while using yarn pnp for module loading.
This file contains 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
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