const fs = require("fs"); const nodePath = require("path"); // import * as fs from "fs"; const folder = "./"; const condition = ["node_modules", "compile"]; let arr: string[] = []; main(folder, (val) => { if (!/.js$/.test(val)) return; arr.push(val); }).then(() => { arr.forEach((src) => { // console.log(src, "forEach", nodePath.resolve(src)); let srcFile = fs.readFileSync(nodePath.resolve(src)).toString(); const analyseRes = analyzeModule(srcFile); if ( analyseRes.modulePaths.length === 0 || analyseRes.startMark === -1 || analyseRes.endMark === -1 ) return; analyseRes.modulePaths.forEach( (module) => (srcFile = loadModule(srcFile, module)) ); srcFile = eraseModuleMark( srcFile, analyseRes.startMark - startMarkStr.length, analyseRes.endMark + endMarkStr.length ); fs.writeFileSync(src, srcFile); console.log("load modules for: " + src); }); }); /** * * @param filePath file path * @returns ['common/js/request.js','common/js/test.js', ...] */ const startMarkStr = "//@LoadModuleStart@"; const endMarkStr = "//@LoadModuleEnd@"; const analyzeModule = ( file: string ): { modulePaths: string[]; startMark: number; endMark: number } => { const startMark = file.indexOf(startMarkStr) + startMarkStr.length; const endMark = file.indexOf(endMarkStr); if (endMark === -1 || startMark === -1) return { modulePaths: [], startMark, endMark }; const modules = file.substring(startMark, endMark); const modulePaths = modules.replace(/\n|\/\//g, "").split("//"); return { modulePaths, startMark, endMark }; }; const loadModule = (src: string, moduleFileSrc: string) => { const moduleFile = fs.readFileSync(moduleFileSrc).toString(); return (src = "\n//--------------\n" + moduleFile + "\n//--------------\n" + src); }; const eraseModuleMark = ( file: string, startMark: number, endMark: number ): string => { return file.substring(0, startMark) + file.substring(endMark); }; async function main(folder: string, callback: (val: string) => void) { const curDir = path(folder); await iterate(curDir); async function iterate(root: string) { let task; try { task = fs.readdirSync(root).map(async (val: string) => { const tmp = path(root) + val; if (await isFile(tmp)) filter(tmp) && callback(tmp); else { const nextPath = path(tmp); filter(nextPath) && (await iterate(nextPath)); } }); } catch (err) { console.log(err); } return Promise.all(task); } } function path(dir: string) { const temp = dir.replace(/\\/g, "/"); if (temp.endsWith("/")) return temp; return temp + "/"; } function isFile(dir: string) { return new Promise((resolve, reject) => { fs.stat(dir, (err: object, stat) => { if (err) reject(err); resolve(stat.isFile()); }); }); } function filter(path: string) { return !condition.find((val) => path.indexOf(val) !== -1); }
标签:src,return,string,nodejs,startMark,引入,endMark,组件,const From: https://www.cnblogs.com/laremehpe/p/17996906