als-require
Version:
A utility for using CommonJS require in the browser and creating bundles.
45 lines (39 loc) • 1.93 kB
JavaScript
const packageJsonCache = {}
async function getNodeModules(nodeModules, children, content, Require, logger, cyclicDependencies) {
const { standartNodeModules } = Require;
if (nodeModules.length === 0) return content
for (let { match, modulePath } of nodeModules) {
const r = new RegExp(`require\\((["'\`])${modulePath}["'\`]\\)`)
const replaceAndWarn = () => {
content = content.replace(r, '{}')
logger.warn(`The module "${modulePath}" can't be imported and will be replaced with {}`)
}
if (modulePath.startsWith('node:') || standartNodeModules.includes(modulePath)) { replaceAndWarn(); continue; }
let fullPath, relativePath, filename, moduleDir = modulePath
if (modulePath.includes('/')) {
const arr = modulePath.split('/')
moduleDir = arr.shift()
relativePath = arr.join('/')
}
let pkgJsonPath = `/node_modules/${moduleDir}/package.json`
const exists = await fetch(pkgJsonPath, { method: 'HEAD' })
if (exists.ok === false) { replaceAndWarn(); continue; }
if (packageJsonCache[pkgJsonPath]) filename = packageJsonCache[pkgJsonPath]
else {
const { main = 'index.js' } = await Require.fetch(pkgJsonPath, 'json')
packageJsonCache[pkgJsonPath] = main
filename = main
}
if (relativePath) fullPath = `/node_modules/${moduleDir}/${relativePath}`
else fullPath = `/node_modules/${moduleDir}/${filename}`
fullPath = fullPath.replace(/\/\.?\//g, '/')
if (!fullPath.endsWith('.js')) fullPath += '.js'
if (!cyclicDependencies) Require.isCyclyc(fullPath, modulePath)
children.push(fullPath);
if(content) content = content.replace(match, match.replace(r, (m, quoute) => {
return `require(${quoute}${fullPath}${quoute})`
}))
}
return content
}
module.exports = getNodeModules