UNPKG

als-require

Version:

A utility for using CommonJS require in the browser and creating bundles.

40 lines (37 loc) 1.75 kB
const rootPath = process.cwd() const fs = require('fs'), { join } = require('path'); const getFullPath = require('./get-full-path') const getNodeModules = require('./node-modules') function getContents({ contents, fullPath }, Require, cyclicDependencies, logger, plugins) { const getContent = (path) => { if (contents[path] !== undefined) return // allready fetched if (!Require.contents[path]) { let content = fs.readFileSync(join(rootPath, path), 'utf-8') const children = [] content = content.replace(/^(?!\/\/|\/\*.*\*\/).*require\(["'`](.*)["'`]\)/gm, (match, modulePath) => { let fullPath const r = new RegExp(`require\\((["'\`])${modulePath}["'\`]\\)`) if (modulePath.startsWith('.')) fullPath = getFullPath(modulePath, path) else { fullPath = getNodeModules(modulePath, logger) if (fullPath === false) return match.replace(r, '{}') } if (!cyclicDependencies && Require.contents[fullPath] && Require.contents[fullPath].children.includes(path)) { throw `Cyclic dependency between ${path} and ${fullPath}` } children.push(fullPath); return match.replace(r, (m, quoute) => `require(${quoute}${fullPath}${quoute})`) }); Require.contents[path] = { content, children } } let { content, children } = Require.contents[path] const obj = {content,children,path} plugins.forEach(plugin => { plugin(obj) }); contents[path] = obj.content for (let childPath of children) { getContent(childPath) } } getContent(fullPath) } module.exports = getContents