@acot/module-loader
Version:
Load the module according to the naming rule of acot.
80 lines (79 loc) • 2.53 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ModuleLoader = void 0;
const path_1 = __importDefault(require("path"));
const utils_1 = require("@acot/utils");
const debug = require('debug')('acot:module-loader');
class ModuleLoader {
constructor(prefix, config = {}) {
this._cache = new Map();
this._prefix = prefix;
this._config = {
from: process.cwd(),
cache: false,
...config,
};
}
load(name) {
debug('load start: %s', name);
// cache (if needed)
if (this._config.cache) {
if (this._cache.has(name)) {
debug('cache hit: key="%s"', name);
return this._cache.get(name);
}
debug('resolve for module in files because cache not found...');
}
let module;
// file
module = this._tryLoadFile(name);
if (module != null) {
this._setCacheIfNeeded(name, module);
return module;
}
debug('resolve for module in package because file not found...');
// package
module = this._tryLoadPackage(name);
if (module != null) {
this._setCacheIfNeeded(name, module);
return module;
}
throw new ReferenceError(`"${name}" module does not found`);
}
tryLoad(name) {
try {
return this.load(name);
}
catch (e) {
debug('load error: ', e);
return null;
}
}
_tryLoadFile(filepath) {
const fpath = path_1.default.join(this._config.from, filepath);
debug('file load... ("%s")', fpath);
const [module, error] = (0, utils_1.tryResolveModule)(fpath);
if (error) {
debug('file load error:', error);
}
return module;
}
_tryLoadPackage(name) {
const id = (0, utils_1.shorthand2pkg)(name, this._prefix);
debug('package load... ("%s")', id);
const [module, error] = (0, utils_1.tryResolveModule)(id, this._config.from);
if (error) {
debug('package load error:', error);
}
return module;
}
_setCacheIfNeeded(name, module) {
if (this._config.cache) {
this._cache.set(name, module);
}
}
}
exports.ModuleLoader = ModuleLoader;