
通过命令行生成uniapp的pages.json文件主要流程核心代码1 引入必要的依赖2 定义初始变量3 读取目标目录4 生成文件5 配置运行命令主要优势完整代码本文详细介绍如何创建一个自动生成 pages.json 配置文件的Node.js脚本主要用于在vscode下开发uni-app等需要此配置文件的项目。主要流程扫描文件脚本会递归扫描项目 src/pages 目录下的所有 .vue 文件。处理路径将每个 .vue 文件的路径转换为 pages.json 所需的页面路径格式。智能过滤自动排除 components 目录下的文件以及预先定义的默认页面避免重复。生成配置将处理好的页面路径与预定义的全局样式设置合并生成完整的 pages.json 文件内容。输出文件将最终的JSON配置写入到指定的 src/pages.json 文件中。核心代码1 引入必要的依赖constfsrequire(fs);constpathrequire(path);2 定义初始变量constdefaultPages[{path:pages/index/index}];constdefaultSettings{globalStyle:{h5:{animationType:fade-in,animationDuration:300},navigationBarBackgroundColor:#0081ff,navigationBarTitleText:,navigationStyle:custom,navigationBarTextStyle:white}};constinputUrlsrc/pages;constoutputUrlsrc/pages.json;3 读取目标目录递归读取目录中的所有.vue文件/** * param {string} dir - 要读取的目录 * returns {Promisestring[]} .vue文件的完整路径数组 */asyncfunctionreadVueFilesRecursive(dir){letresults[];constentriesawaitfs.promises.readdir(dir,{withFileTypes:true});for(constentryofentries){constfullPathpath.join(dir,entry.name);if(entry.isDirectory()){// 递归读取子目录constsubDirResultsawaitreadVueFilesRecursive(fullPath);resultsresults.concat(subDirResults);}elseif(entry.isFile()entry.name.endsWith(.vue)){// 只处理.vue文件results.push(fullPath);}}returnresults;}4 生成文件异步生成pages.json配置文件/** * 该函数会扫描项目src/pages目录下的所有.vue文件 * 并根据这些文件生成一个包含页面路由信息的pages.json配置文件。 * * returns {Promisevoid} 无返回值的Promise */asyncfunctiongeneratePagesJson(){console.info(正在生成 pages.json...);constprojectRootprocess.cwd();constsrcDirpath.join(projectRoot,inputUrl);constoutputFilepath.join(projectRoot,outputUrl);// 确保输出文件的目录存在constoutputDirpath.dirname(outputFile);if(!fs.existsSync(outputDir)){fs.mkdirSync(outputDir,{recursive:true});console.info(已创建目录:${outputDir});}try{// 递归读取所有.vue文件constvueFilesawaitreadVueFilesRecursive(srcDir);constpages[];// 添加默认页面到pages数组pages.push(...defaultPages);// 遍历所有.vue文件并将其转换为页面路径for(leti0;ivueFiles.length;i){constfilevueFiles[i];constloadpath.relative(projectRoot,file).replace(src\\,).replace(/\\/g,/).replace(/\.vue/g,);// 过滤掉components目录中的文件if(newRegExp(/components/).test(load))continue;// 过滤掉已在默认页面中定义的路径if(defaultPages.findIndex(itemitem.pathload)-1)continue;pages.push({path:load});}// 创建JSON内容constjsonContentJSON.stringify({...defaultSettings,pages:pages},null,2);// 写入文件awaitfs.promises.writeFile(outputFile,jsonContent,utf8);console.info(已更新 pages.json包含${pages.length}个Vue文件);}catch(error){console.error(生成pages.json时出错:${error.message});process.exit(1);}}5 配置运行命令将配置放入到package.json中的scripts下pages:node ./src/utils/generate-pages.js需要运行时直接运行npm run pages主要优势自动化无需手动维护 pages.json 中的页面列表。高效准确新增页面后运行命令即可自动添加减少遗漏和错误。灵活性允许预先设置默认页面和全局样式并支持自定义输入/输出目录。完整代码constfsrequire(fs);constpathrequire(path);constdefaultPages[{path:pages/index/index}];constdefaultSettings{globalStyle:{h5:{animationType:fade-in,animationDuration:300},navigationBarBackgroundColor:#0081ff,navigationBarTitleText:,navigationStyle:custom,navigationBarTextStyle:white}};constinputUrlsrc/pages;constoutputUrlsrc/pages.json;/** * 异步生成pages.json配置文件 * * 该函数会扫描项目src/pages目录下的所有.vue文件 * 并根据这些文件生成一个包含页面路由信息的pages.json配置文件。 * * returns {Promisevoid} 无返回值的Promise */asyncfunctiongeneratePagesJson(){console.info(正在生成 pages.json...);constprojectRootprocess.cwd();constsrcDirpath.join(projectRoot,inputUrl);constoutputFilepath.join(projectRoot,outputUrl);// 确保输出文件的目录存在constoutputDirpath.dirname(outputFile);if(!fs.existsSync(outputDir)){fs.mkdirSync(outputDir,{recursive:true});console.info(已创建目录:${outputDir});}try{// 递归读取所有.vue文件constvueFilesawaitreadVueFilesRecursive(srcDir);constpages[];// 添加默认页面到pages数组pages.push(...defaultPages);// 遍历所有.vue文件并将其转换为页面路径for(leti0;ivueFiles.length;i){constfilevueFiles[i];constloadpath.relative(projectRoot,file).replace(src\\,).replace(/\\/g,/).replace(/\.vue/g,);// 过滤掉components目录中的文件if(newRegExp(/components/).test(load))continue;// 过滤掉已在默认页面中定义的路径if(defaultPages.findIndex(itemitem.pathload)-1)continue;pages.push({path:load});}// 创建JSON内容constjsonContentJSON.stringify({...defaultSettings,pages:pages},null,2);// 写入文件awaitfs.promises.writeFile(outputFile,jsonContent,utf8);console.info(已更新 pages.json包含${pages.length}个Vue文件);}catch(error){console.error(生成pages.json时出错:${error.message});process.exit(1);}}/** * 递归读取目录中的所有.vue文件 * param {string} dir - 要读取的目录 * returns {Promisestring[]} .vue文件的完整路径数组 */asyncfunctionreadVueFilesRecursive(dir){letresults[];constentriesawaitfs.promises.readdir(dir,{withFileTypes:true});for(constentryofentries){constfullPathpath.join(dir,entry.name);if(entry.isDirectory()){// 递归读取子目录constsubDirResultsawaitreadVueFilesRecursive(fullPath);resultsresults.concat(subDirResults);}elseif(entry.isFile()entry.name.endsWith(.vue)){// 只处理.vue文件results.push(fullPath);}}returnresults;}// 执行脚本generatePagesJson();