als-require
Version:
A utility for using CommonJS require in the browser and creating bundles.
30 lines (28 loc) • 1.36 kB
JavaScript
async function getContents({contents, fullPath},Require,cyclicDependencies, logger, plugins=[]) {
const getContent = async (path) => {
if (contents[path] !== undefined) return // allready fetched
if (!Require.contents[path]) {
let content = await Require.fetch(path)
const children = [], nodeModules = [];
content = content.replace(/^(?!\/\/|\/\*.*\*\/).*require\(["'`](.*)["'`]\)/gm, (match, modulePath) => {
if (!modulePath.startsWith('.')) {
nodeModules.push({ match, modulePath })
return match
}
const fullPath = getFullPath(modulePath, path)
if(!cyclicDependencies) Require.isCyclyc(fullPath, path)
children.push(fullPath);
return match.replace(modulePath, fullPath)
});
content = await getNodeModules(nodeModules, children, content,Require, logger, cyclicDependencies)
Require.contents[path] = { content, children }
}
const { content, children } = Require.contents[path]
const obj = {content,children,path}
plugins.forEach(plugin => { plugin(obj) });
contents[path] = obj.content
await Promise.all(children.map(childPath => getContent(childPath)))
}
await getContent(fullPath)
}
module.exports = getContents