als-require
Version:
A utility for using CommonJS require in the browser and creating bundles.
50 lines (43 loc) • 2.18 kB
JavaScript
class Require {
static standartNodeModules = ["assert", "async_hooks", "buffer", "child_process", "cluster", "console", "constants", "crypto", "dgram", "diagnostics_channel", "dns", "domain", "events", "fs", "http", "http2", "https", "inspector", "module", "net", "os", "path", "perf_hooks", "process", "punycode", "querystring", "readline", "repl", "stream", "string_decoder", "sys", "timers", "timers/promises", "tls", "trace_events", "tty", "url", "util", "v8", "vm", "wasi", "worker_threads", "zlib", "test", "abort_controller"];
static contents = {}
static plugins = []
static cyclicDependencies = false
static logger = console
static version
static isCyclyc(fullPath, path) {
if (this.contents[fullPath] && this.contents[fullPath].children.includes(path)) {
throw `cyclic dependency between ${path} and ${fullPath}`
}
}
static async fetch(path, type = 'text') {
if (this.version) path += '?version=' + this.version
let response = await fetch(path)
if (!response.ok) console.error(`HTTP error! status: ${response.status}`);
return await response[type]()
}
static async getModule(path, options = {},...params) {
const mod = new Require(path)
await mod.getContent(options)
const fn = await mod.fn(options)
return fn(...params)
}
constructor(path,options = {}) {
this.contents = {}
this.path = path
this.fullPath = getFullPath(path, location.pathname)
this.contentReady = false
this.options = options
}
async getContent(options = {}) {
let { plugins = [], cyclicDependencies = Require.cyclicDependencies, logger = Require.logger } = {...this.options,...options}
plugins = [...Require.plugins, ...plugins].filter(p => typeof p === 'function')
if (this.contentReady) return this
await getContents(this, Require, cyclicDependencies, logger, plugins)
this.keys = orderKeys(Object.keys(this.contents),Require).reverse()
this.contentReady = true
return this
}
fn(options = {}) { return getFn(this, options) }
};
module.exports = Require