UNPKG

requirez

Version:

module require loader with no cache and dir concat

109 lines (86 loc) 2.08 kB
'use strict'; const kit = require('./kit.js'); class Loader{ /** * @constructor * @param {object} op */ constructor(op){ this.config = { root: '' , extname: '.js' // , dirExtname: '/' , codeExtname: '.code' , forceUpdate: false }; this.param = {}; this.alias = {}; this.cache = {}; this._setConfig(op); } _setConfig(op){ Object.assign(this.config, op); ['param', 'alias'].forEach((key)=>{ Object.assign(this[key], this.config[key]); delete this.config[key]; }); this.config.root = kit.toUnixPath(this.config.root || process.cwd(), 1); } /** * 加载一个模块或从缓存中读取 * @param {string} name */ get(name){ let path, rs; name = name == null ? '' : name.toString(); //* parse param name = name.indexOf('{') === -1 ? name : kit.parseString(name, this.param); //* parse alias path = this.alias[name] || name; if(path && ['object', 'function'].indexOf(typeof path) > -1){ return path; } //* get path path = kit.isAbsolutePath(path) ? path : this.config.root + path; //* get extname let extname = kit.extname(path); if(extname === this.config.codeExtname){ path = kit.toUnixPath(path, 1); kit.concatDirFiles(path); path += 'index.js'; }else if(extname === ''){ path += this.config.extname; } //* is clear cache if(this.config.forceUpdate){ delete this.cache[path]; this.clear(path); } //* is cache exists if(path in this.cache){ rs = this.cache[path]; }else{ rs = this.cache[path] = require(path); } return rs; } /** * 清除缓存 * @param {string} id - module id */ clear(id){ if(id == null){ let key; for(key in require.cache){ delete require.cache[key] } }else{ id = id.charAt(1) !== ':' ? id : id.replace(/\//g, '\\'); delete require.cache[id]; // console.log('<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<') // console.log('clear cache', id) // console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>') } } } module.exports = Loader;