als-require
Version:
A utility for using CommonJS require in the browser and creating bundles.
225 lines (202 loc) • 9.27 kB
Markdown
## API
### NodeJs version
```js
/**
* The `Require` class handles modular dynamic loading,
* dependency resolution, and cyclic dependency detection.
*/
class Require {
/**
* Stores the contents of all loaded modules.
* Each entry maps a module path to its content and children (dependencies).
* @type {Object<string, { content: string, children: string[] }>}
* @static
*/
static contents = {};
/**
* List of global plugins to process module contents.
* Plugins are functions that modify a module's content or children, without replacing the object reference.
* For example, a plugin can transform `module.content` using `module.content.replace(...)`.
* @type {Array<Function>}
* @static
*/
static plugins = [];
/**
* Flag to enable or disable cyclic dependency.
* When enabled, it allows loading modules that depend on each other recursively.
* @type {boolean}
* @static
*/
static cyclicDependencies = false;
/**
* Logger for warnings and error messages.
* Defaults to the global `console` object but can be overridden with a custom logger.
* @type {Console}
* @static
*/
static logger = console;
/**
* Retrieves a module by its path and options.
* This is a shortcut for instantiating a `Require` object and calling its `fn` method.
* @param {string} path - Path to the module.
* @param {Object} [options] - Options for the module loading.
* @param {string} [options.scriptBefore] - Code to prepend before the module's execution.
* @param {string} [options.scriptAfter] - Code to append after the module's execution.
* @param {string[]} [options.parameters] - Parameters to pass into the generated function.
* @param {Function[]} [options.plugins] - Array of plugin functions.
* @param {boolean} [options.cyclicDependencies] - Whether to allow cyclic dependencies.
* @param {Console} [options.logger] - Custom logger for warnings and errors.
* @returns {Function} - The dynamically generated function for the module.
* @static
*/
static getModule(path, options = {}) {
// Creates a new Require instance and calls its `fn` method to generate the module's function.
return new Require(path, options).fn(options);
}
/**
* Creates a `Require` instance for managing a specific module and its dependencies.
* The constructor handles loading the module's contents, resolving dependencies, and applying plugins.
* @param {string} path - Path to the root module to be loaded.
* @param {Object} [options] - Options for module handling.
* @param {Function[]} [options.plugins] - Plugins to modify module content or structure.
* @param {boolean} [options.cyclicDependencies] - Whether to detect cyclic dependencies.
* @param {Console} [options.logger] - Custom logger for warnings and errors.
*/
constructor(path, options = {}) {
const {
plugins = [],
cyclicDependencies = Require.cyclicDependencies,
logger = Require.logger,
} = options;
// Merge global plugins with instance-specific plugins.
const combinedPlugins = [...Require.plugins, ...plugins].filter(p => typeof p === 'function');
this.contents = {}; // Stores the current module's contents and dependencies.
this.path = path; // Path to the root module.
this.fullPath // will include full path for module
// In NodeJs Require loads the module's contents and applies plugins.
this.keys // Keys are the paths of all loaded modules, sorted in reverse order.
}
/**
* Generates a function for the module that incorporates options for execution.
* The function includes dynamically generated code that can be executed with custom parameters.
* @param {Object} [options] - Options for function generation.
* @param {string} [options.scriptBefore] - Code to prepend before the module's execution.
* @param {string} [options.scriptAfter] - Code to append after the module's execution.
* @param {string[]} [options.parameters] - Parameters to pass into the generated function.
* @returns {Function} - The dynamically generated function for the module.
*/
fn(options = {}) {}
/**
* Generates a string representation of the function for the module.
* Useful for embedding the module in scripts or HTML, with an optional function name.
* @param {Object} [options] - Options for function generation.
* @param {string} [options.scriptBefore] - Code to prepend before the module's execution.
* @param {string} [options.scriptAfter] - Code to append after the module's execution.
* @param {string[]} [options.parameters] - Parameters to pass into the generated function.
* @param {string} [options.name] - If presented, replaces the anonymous function name with the provided name.
* @returns {string} - The string representation of the function.
*/
stringFn(options = {}) {}
}
```
### Browser version
```js
/**
* The `Require` class provides modular loading, dependency resolution,
* cyclic dependency detection, and fetch-based loading for both server and browser environments.
*/
class Require {
/**
* A list of standard Node.js modules that are automatically excluded from fetching.
* @type {string[]}
* @static
*/
static standartNodeModules = [...];
/**
* Stores the contents of all loaded modules.
* Each entry maps a module path to its content and dependencies.
* @type {Object<string, { content: string, children: string[] }>}
* @static
*/
static contents = {};
/**
* List of global plugins to process module contents.
* Plugins are functions that modify a module's content or structure.
* @type {Array<Function>}
* @static
*/
static plugins = [];
/**
* Flag to enable or disable cyclic dependency detection.
* @type {boolean}
* @static
*/
static cyclicDependencies = false;
/**
* Logger for warnings and error messages.
* Default is the `console` object but can be replaced with a custom logger.
* @type {Console}
* @static
*/
static logger = console;
/**
* Version string to append to fetched module URLs for cache-busting.
* @type {string | undefined}
* @static
*/
static version;
/**
* Checks if a cyclic dependency exists between two modules and throws an error if detected.
* @param {string} fullPath - The full path of the dependent module.
* @param {string} path - The path of the current module.
* @throws {Error} Throws an error if a cyclic dependency is detected and cyclicDependencies=false.
* @static
*/
static isCyclyc(fullPath, path) {}
/**
* Fetches a resource from a given path and returns its content.
* Supports different response types such as 'text', 'json', etc.
* @param {string} path - The URL or path to fetch.
* @param {string} [type='text'] - The type of the response (e.g., 'text', 'json').
* @returns {Promise<any>} Resolves with the fetched content in the specified format.
* @static
*/
static async fetch(path, type = 'text') {}
/**
* Asynchronously loads a module and its dependencies, returning a function for execution.
* @param {string} path - Path to the module.
* @param {Object} [options] - Options for module loading.
* @returns {Promise<Function>} Resolves to the dynamically generated function for the module.
* @static
*/
static async getModule(path, options = {}) {}
/**
* Creates a `Require` instance for managing a specific module.
* The constructor initializes the module's path, content readiness state, and options.
* @param {string} path - Path to the root module to be loaded.
* @param {Object} [options] - Options for module handling.
*/
constructor(path, options = {}) {
this.contents = {}; // Stores the current module's contents and dependencies.
this.path = path; // Path to the root module.
this.fullPath; // Resolves the full path based on the current location.
this.contentReady = false; // Indicates if the module's content has been fully loaded.
this.options = options; // Custom options for module handling.
}
/**
* Asynchronously loads the module's content and dependencies.
* Applies plugins and detects cyclic dependencies if enabled.
* @param {Object} [options] - Options for content loading.
* @returns {Promise<Require>} Resolves to the current instance after loading content.
*/
async getContent(options = {}) {}
/**
* Generates a function for the module that incorporates execution options.
* The function includes dynamically generated code that can be executed with custom parameters.
* @param {Object} [options] - Options for function generation.
* @returns {Function} - The dynamically generated function for the module.
*/
fn(options = {}) {}
}
module.exports = Require;
```