UNPKG

tubao-dir

Version:

可以自由灵活的获取到特定目录的文件名字数组以便于配合webpack进行整体工程打包

114 lines (97 loc) 3.4 kB
import * as path from 'path'; import * as fs from 'fs'; /** * 兔宝世界webpack构建多文件类库目录配置获取 */ export class tubaoDir { /**结果存储目录 */ private entryMap: string[] = []; /**排除文件类型 */ private excludeType: string[]; /**排除文件名字 */ private excludeName: string[] = []; /** * 兔宝世界开源webpack多文件类库打包工具目录获取 * @param {string} path 指定要获取的目录 * @param {string} excludeType 指定排除文件类型 * @param {string} excludeName 指定排除文件名字 */ public constructor(excludeType: string[] = [], excludeName: string[] = []) { this.mapDir = this.mapDir.bind(this); this.readDir = this.readDir.bind(this); //重置定位作用域 this.excludeType = excludeType; //排除文件类型 this.excludeName = excludeName; //排除文件名字 } /** * 读取特定目录 * @param {string} path 要查询的目录 * @return {string[]} 返回的目录 */ public read(path: string): string[] { this.entryMap = []; //目录内容置空 this.readDir(path) //遍历目录 console.log(this.entryMap) //结果 return this.entryMap; //返回目录内容 } /** * 读取目录 * @param {string} dir 起步目录位置 */ private readDir(dir: string) { var files: string[] = fs.readdirSync(dir) //文件列表 if (!files) { console.log(files); return null; } //读取目录错误 for (var key in files) { //遍历 this.mapDir(files[key], dir); } } /** * 遍历目录 * @param {string} fileName 文件名字 * @param {string} dir 文件所在目录 */ private mapDir(fileName: string, dir: string) { var allDir: string = path.join(dir, fileName); //全部目录位置 var stats: fs.Stats = fs.statSync(allDir); //文件信息 if (!stats) { console.log('获取文件和目录信息stats获取失败'); return; } if (stats.isDirectory()) { //是目录 this.readDir(allDir); //读取目录 } else if (stats.isFile()) {//是文件 this.fileDispose(allDir, dir, fileName) //处理文件 } } /** * 文件处理 * @param {string} allDir 全部目录 * @param {string} dir 目录 * @param {string} fileName 文件名字 */ private fileDispose(allDir: string, dir: string, fileName: string) { if (this.excludeType.includes(path.extname(allDir))) { // 排除目录下的指定文件类型 console.log(`排除文件类型--名字:${allDir}--目录:${allDir}`) return } if (this.excludeName.indexOf(fileName.split('.')[0]) != -1) { // 排除目录下的指定文件 console.log(`排除文件名字--名字:${fileName} 目录:${allDir}`) return } console.log(`已记录文件:${fileName}--目录:${dir}`) this.entryMap.push("./"+allDir); //结果存储目录 } }