Skip to content

Instantly share code, notes, and snippets.

@SevenOutman
Last active July 20, 2023 06:59
Show Gist options
  • Save SevenOutman/6896b10db29a7d3d97672674cc87e540 to your computer and use it in GitHub Desktop.
Save SevenOutman/6896b10db29a7d3d97672674cc87e540 to your computer and use it in GitHub Desktop.
require.context polyfill
// 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