Renderer/assets/Scripts/compiler/require_polyfill.js
2024-07-02 17:07:16 -04:00

44 lines
1.4 KiB
JavaScript

/**
* Caches loaded modules
*/
let REQUIRE_CACHE = { }
/**
* Used if the module is directly executed instead of being require'd for some reason
*/
let exports = { }
/**
* Imports a module
* @param {*} path The path of the module
* @param {*} cwd The current working directory
*/
const require = (path) => {
loggerScripts.DEBUG('Require path ' + path)
let normalizedFilePath = FILE_RESOLUTION_getFilePath(path)
if(!!REQUIRE_CACHE[normalizedFilePath]){
return REQUIRE_CACHE[normalizedFilePath].exports
} else if(!!COMPILER_fileMap[normalizedFilePath]?.content) {
const code = COMPILER_fileMap[normalizedFilePath].moduleContent
let exports = new Function(code)()
//create module object
const module = {
exports: exports,
exportedValues: Object.keys(exports),
}
REQUIRE_CACHE[normalizedFilePath] = module
loggerScripts.INFO("[require] CREATE MODULE " + normalizedFilePath)
return module.exports
} else {
const errorMsg = "FAILED TO REQUIRE FILE " + normalizedFilePath
loggerScripts.WARNING(errorMsg)
loggerScripts.WARNING('Module value:')
loggerScripts.WARNING(Object.keys(REQUIRE_CACHE?.[normalizedFilePath]) + '')
loggerScripts.WARNING('Require cache contents:')
loggerScripts.WARNING(Object.keys(REQUIRE_CACHE) + '')
throw new Error(errorMsg)
}
}