This script is based on this StackOverflow answer, with some modifications to fix its issues.
Last active
July 20, 2023 06:59
-
-
Save SevenOutman/6896b10db29a7d3d97672674cc87e540 to your computer and use it in GitHub Desktop.
require.context polyfill
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
// Original by Edmundo Santos at https://stackoverflow.com/a/42191018 | |
// Modified by Doma (https://github.com/SevenOutman) | |
// This condition actually should detect if it's an Node environment | |
if (typeof require.context === 'undefined') { | |
const fs = require('fs'); | |
const path = require('path'); | |
require.context = (base = '.', scanSubDirectories = false, regularExpression = /\.js$/) => { | |
const context = path.resolve(__dirname, base); | |
const files = {}; | |
function readDirectory(directory) { | |
fs.readdirSync(directory).forEach((file) => { | |
const fullPath = path.resolve(directory, file); | |
if (fs.statSync(fullPath).isDirectory()) { | |
if (scanSubDirectories) readDirectory(fullPath); | |
return; | |
} | |
if (!regularExpression.test(fullPath)) return; | |
files['./' + path.relative(context, fullPath)] = true; | |
}); | |
} | |
readDirectory(context); | |
function Module(file) { | |
return require(path.resolve(context, file)); | |
} | |
Module.keys = () => Object.keys(files); | |
return Module; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment