Last active
August 3, 2023 20:13
-
-
Save cyco130/c6e2d95e108fd496678e6fced181299c to your computer and use it in GitHub Desktop.
A toy CommonJS implementation
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
import fs from "node:fs"; | |
import path from "node:path"; | |
import url from "node:url"; | |
const cache = {}; | |
function createRequire(filename) { | |
function require(specifier) { | |
const resolved = require.resolve(specifier); | |
if (resolved in cache) { | |
return cache[resolved].exports; | |
} | |
const contents = fs.readFileSync(resolved, "utf8"); | |
const module = { | |
loaded: false, | |
exports: {}, | |
}; | |
const fn = new Function( | |
"module", | |
"exports", | |
"require", | |
"__dirname", | |
"__filename", | |
contents, | |
); | |
let innerRequire; | |
cache[resolved] = module; | |
fn( | |
module, | |
module.exports, | |
function require(specifier) { | |
if (!innerRequire) { | |
innerRequire = createRequire(resolved); | |
} | |
return innerRequire(specifier); | |
}, | |
path.dirname(resolved), | |
resolved, | |
); | |
module.loaded = true; | |
return module.exports; | |
} | |
require.resolve = (specifier) => { | |
let resolved = path.resolve(path.dirname(filename), specifier); | |
if (fs.existsSync(resolved)) { | |
return resolved; | |
} | |
if (fs.existsSync(resolved + ".js")) { | |
return resolved + ".js"; | |
} | |
}; | |
require.cache = cache; | |
return require; | |
} | |
const require = createRequire(url.fileURLToPath(import.meta.url)); | |
require(process.argv[2]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment