als-require
Version:
A utility for using CommonJS require in the browser and creating bundles.
48 lines (44 loc) • 1.56 kB
JavaScript
const parseError = require('./parse-error')
function getFn(obj, options={}) {
const { scriptBefore='', scriptAfter='', parameters=[] } = options
function buildFn(fnBody,path) {
return /*js*/`modules['${path}'] = function ____(){
const module = { exports: {} }
const exports = module.exports
${fnBody}
return module.exports;
};`
}
const before = [
parseError.toString(),
/*js*/`function require(path) {
if(typeof modules[path] === 'function' && modules[path].name === '____') modules[path] = modules[path]()
return modules[path] || null
};`,
scriptBefore,
].join('\n')
const modulesLines = {};
let curLastLine = 3+before.split('\n').length;
let lastModule
const fns = obj.keys.map((path, i) => {
let code = buildFn(obj.contents[path],path)
if (i === obj.keys.length - 1) lastModule = path
modulesLines[path] = { from: curLastLine + 1 }
curLastLine += code.split('\n').length
modulesLines[path].to = curLastLine
return code
}).join('\n')
const body = [
before,
'try {',
fns,
`let result = modules['${lastModule}']()`,
scriptAfter,
`return result`,
`} catch (error) { parseError(error, modulesLines, curLastLine) }`,
].join('\n')
parameters.push('modules={}',`curLastLine = ${curLastLine}`,`modulesLines = ${JSON.stringify(modulesLines)}`)
const fn = new Function(parameters.join(','), body)
return fn
}
module.exports = getFn