Skip to content

Instantly share code, notes, and snippets.

@up209d
Created March 15, 2018 23:08
Show Gist options
  • Save up209d/e358d918f1a861683fbe304e216af76f to your computer and use it in GitHub Desktop.
Save up209d/e358d918f1a861683fbe304e216af76f to your computer and use it in GitHub Desktop.
Require Hack which get stats from webpack to render assets paths
// Require Hack which get stats from webpack to render assets paths
let Module = require('module');
let _require = Module.prototype.require;
Module.prototype.require = function() {
let currentPath = arguments[0];
// let currentFilename = currentPath.substring(currentPath.lastIndexOf('/')+1,currentPath.length);
// let currentFileext = currentPath.substring(currentPath.lastIndexOf('.')+1,currentPath.length);
// console.log(currentFilename,currentFileext,currentFileext.length);
try {
return _require.call(this,arguments[0]);
} catch (err) {
let currentStats = getStats();
if (currentStats) {
let currentModules = currentStats.modules;
let userRequestList = {};
// Create this refs array for querying performance
currentModules.forEach((currentModule)=>{
if (currentModule.reasons && currentModule.assets) {
if (currentModule.reasons.length > 0 && currentModule.assets.length > 0) {
currentModule.reasons.forEach((reason)=>{
userRequestList[reason.userRequest] = currentModule.assets[0];
})
}
}
});
// console.log('====== NODE FALLBACK: ',currentPath);
// err: {"code":"MODULE_NOT_FOUND"}
// It is unsupport importing file, also can be the relative path is not valid
// We dont care, we just want to figure out where webpack put that file in real bundle folder
// let foundIndex = currentModules.findIndex(function(currentModule){
// if (currentModule.reasons.length) {
// return currentModule.reasons[0].userRequest === currentPath;
// } else {
// return false;
// }
// });
// return foundIndex >= 0 ? currentStats.publicPath + currentModules[foundIndex].assets[0] : currentPath;
// console.log(userRequestList);
return userRequestList[currentPath] ? currentStats.publicPath + userRequestList[currentPath] : currentStats.publicPath + currentPath;
} else {
console.log('REQUIRE ERROR: ',err); //err
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment