Routing management
Because of the number of project pages, managing page routing in UNI-app was too cumbersome, so this method was found with great difficulty.
Building file architecture
Create a New Router folder in the SRC folder home and follow the following buildfile structure.
├─ ├─ pagesA # ├─ inner. Js # ├ ─ 088 (PDF, PDF, PDF, PDF) ├ ─ 088 (PDF, PDF, PDF, PDFCopy the code
Write the build.js file
The build.js file, the main file, is written with nodejs to compile pages. Json.
-
The code is as follows:
const fs = require('fs') const path = require('path') const router = require('./index.js') // Convert the child routing module configuration file to uniAPP configuration file format const buildRouter = route= > { const res = [] const { baseUrl, children } = route function builder (baseUrl, children) { children.forEach(i= > { if (i.children) { builder(baseUrl + i.path + '/', i.children) } else { const obj = { path: baseUrl + i.path, style: { navigationBarTitleText: i.name } } Object.keys(i).forEach(ii= > { !['path'.'name'].includes(ii) && (obj.style[ii] = i[ii]) }) res.push(obj) } }) } builder(baseUrl, children) return res } // Automatically loads the './modules' subrouting configuration file const getRouter = () = > { const srcPath = path.resolve(__dirname, './modules') const result = fs.readdirSync(srcPath) let router = [] result.forEach(r= > { const route = require('./modules/' + r) router = [ ...router, ...buildRouter(route)] }) return router } // Build pages and write the pages. Json file router.pages = getRouter() fs.writeFile( __dirname + '/.. /pages.json'.// I indent pages. Json with two Spaces. If you like tabs, change the third parameter to \t JSON.stringify(router, null.' '), e= > e ? console.error(e) : console.log('pages. Json configuration file updated successfully '))Copy the code
-
If updated, you can see the source code of the original author.
Write the index.js file
This file is used to write content other than the Pages field in the pages. Json file, refer to the official configuration. My content is as follows:
module.exports = {
easycom: {
autoscan: true.custom: {
// Uni-UI rule configuration is as follows
"^uni-(.*)": "@dcloudio/uni-ui/lib/uni-$1/uni-$1.vue"."^u-(.*)": "uview-ui/components/u-$1/u-$1.vue"."^my-(.*)": "@/components/my-$1/my-$1.vue".// Match the vue file in the Components directory}},tabBar: {
color: "#7A7E83".selectedColor: "#216df6".borderStyle: "black".backgroundColor: "#ffffff".list: [{pagePath: "pages/index/index".iconPath: "static/image/tabbar/home.png".selectedIconPath: "static/image/tabbar/home-1.png".text: "Home page"}, {pagePath: "pages/record/index".iconPath: "static/image/tabbar/record.png".selectedIconPath: "static/image/tabbar/record-1.png".text: "Medical records"}, {pagePath: "pages/userCenter/index".iconPath: "static/image/tabbar/userCenter.png".selectedIconPath: "static/image/tabbar/userCenter-1.png".text: "Personal Center",}]},globalStyle: {
navigationBarTextStyle: "black".navigationBarTitleText: "Patient end".navigationBarBackgroundColor: "#ffffff".backgroundColor: "#F8F8F8".h5: {
titleNView: false,}}};Copy the code
Write modules subrouting files
Export an object as follows:
module.exports = {
baseUrl: 'pages/small/'.children: [{path: 'register'.name: 'registered'.'app-plus': {
titleNView: {
buttons: [{text: 'message'.fontSize: '16px'}]}}}, {path: 'login'.name: 'login'}}]Copy the code
baseUrl
: Directory where these files are stored. I can break it down, and I can write these paths over and over again.children
: Path and title of each page in this subpath.Other Configuration Items
: If you need to use other configuration items, just write them. For example, the code aboveapp-plus
.instructions
: and hereuniapp
The defaultpages.json
The format is slightly different in mybuild.js
in-filebuildRouter()
The function does this data format conversion. The goal is to make our child routing configuration code more concise.
Subroutes are nested
Although the subpaths are divided into different files, they may need to be nested. So I updated the code to add this notation.
module.exports = {
baseUrl: 'pages/site/'.children: [{path: 'index'.name: 'home'.'app-plus': { titleNView: { buttons: [{text:'message'.fontSize:'16px'}]}}}, {path: 'tobeAcceptedTask'.name: 'Duty to Be accepted'}, {path: 'task'.// show the nested notation
children: [{path: 'index'.name: 'task' },
{
path: 'deliveryMerchant'.name: 'Delivery Merchant'.'app-plus': { titleNView: { buttons: [{text:'Map Mode'.fontSize:'14px'.width: '76px'}]}}}, {path: 'map'.name: 'Map Mode'.'app-plus': { titleNView: false}}, {path: 'goodsList'.name: 'List of Goods' },
{ path: 'receivables'.name: 'payment'},]},]}Copy the code
Subcontract configuration and subcontract preload configuration
My project was relatively large, and the generated small program exceeded 2M, so I could not upload the preview, so I carried out simple subcontracting.
build.js
The following code is added to the file for modificationpages
Configuration:
// Automatically load subcontracting files in the './pagesA' directory
const getSubPackages = () = > {
const srcPath = path.resolve(__dirname, "./pagesA");
const result = fs.readdirSync(srcPath);
let router = [];
result.forEach((r) = > {
const route = require("./pagesA/" + r);
router = [...router, ...buildRouter(route)];
});
return[{root: "pagesA".pages: router,
},
];
};
// Build getSubPackages and write the pages. Json file
router.subPackages = getSubPackages();
fs.writeFile(
__dirname + "/.. /pages.json".// I indent pages. Json with two Spaces. If you like tabs, change the third parameter to \t
JSON.stringify(router, null.""),
(e) = > (e ? console.error(e) : console.log("Pages. Json Subcontract configuration file updated successfully")));Copy the code
index.js
Add the following code to theSubcontract preload configuration
, improve the page opening speed:
preloadRule: {
"pages/index/index": {
network: "all".packages: ["pagesA"],}},Copy the code
use
After building this code, run the build.js file directly from the command line to generate the pages. Json configuration file in the SRC folder. The code is as follows:
node src/router/build.js
Copy the code
Special instructions
It should be noted here that I am using the CLI tool to generate the project, the root directory above becomes the project SRC directory. If the project is generated using the HBuilder GUI interface, the root directory is the project root directory.
Reference documentation
Dynamic generation of uniApp configuration file pages. Json solution