als-require
Version:
A utility for using CommonJS require in the browser and creating bundles.
30 lines (27 loc) • 1.41 kB
JavaScript
const getFullPath = require('./get-full-path');
const calledFrom = require('als-called-from');
const getContents = require('./get-contents');
const getFn = require('./get-fn')
const orderKeys = require('./order-keys')
class Require {
static contents = {}
static plugins = []
static cyclicDependencies = false
static logger = console
static getModule(path, options={}) { return new Require(path, options).fn(options) } //{ scriptBefore, scriptAfter, parameters, plugins, cyclicDependencies, logger }
constructor(path, options = {}) {
let { plugins = [], cyclicDependencies = Require.cyclicDependencies, logger = Require.logger } = options
plugins = [...Require.plugins, ...plugins].filter(p => typeof p === 'function')
this.contents = {};
this.path = path;
this.fullPath = getFullPath(path, calledFrom().replace(process.cwd(), ''));
getContents(this, Require, cyclicDependencies, logger, plugins)
this.keys = orderKeys(Object.keys(this.contents),Require).reverse()
}
fn(options = {}) { return getFn(this, options) } // { scriptBefore, scriptAfter, parameters }
stringFn(options = {}) { // { scriptBefore, scriptAfter, parameters, name }
let fn = getFn(this, options).toString()
return options.name ? fn.replace('function anonymous', 'function ' + options.name) : fn
}
}
module.exports = Require