Solutions for uni-app and applet projects to split pages.json files, dynamically generate pages.json files, and dynamically generate subpackage configuration pages.json files

Dynamically generate pages.json file

The applet project splits the pages.json file, dynamically generates the pages.json file, and finally obtains the following directory structure:
insert image description here

common/router/modules/*: 依据模块划分不同页面配置js文件

common/router/index.js: 对应pages.js中除了页面pages配置的参数外,其他在pages.js文件中配置的参数都放这里面

common/router/build.js:核心文件,主要是读取modules/目录下的文件以及router/index.js文件然后动态生成pages.json文件

Divide different page configuration js files according to modules

Create user.js and process.js files here as an example

user.js

baseUrl:页面文件存放的实际位置目录

children:相当于是在pages.json文件中对pages参数项进行相关页面配置
module.exports = {
    
    
    baseUrl: 'pages/user/',
    children: [
        {
    
    
            path: 'me',
            text: '个人中心',
        },
        {
    
    
            path: 'Logout',
            text: '退出',
        }
    ]
}

process.js

module.exports = {
    
    
    baseUrl: 'pages/process/',
    children: [
        {
    
    
            path: 'core/ProcessList',
            name: 'ProcessList',
            text: '流程列表',
        }
    ]
}

index.js (configure pages.json)

The index.js file corresponds to the parameters configured in the pages.js except for the parameters configured in the pages.js file, and other parameters configured in the pages.js file are placed here

module.exports = {
    
    
    "easycom": {
    
    
        "^u-(.*)": "uview-ui/components/u-$1/u-$1.vue"
    },
    "globalStyle": {
    
    
        "navigationBarTextStyle": "black",
        "navigationBarTitleText": "uni-app",
        "navigationBarBackgroundColor": "#F8F8F8",
        "backgroundColor": "#F8F8F8"
    },
    "tabBar": {
    
    
        "color": "#7A7E83",
        "selectedColor": "#3cc51f",
        "borderStyle": "black",
        "backgroundColor": "#ffffff",
        "list": [
            {
    
    
                "pagePath": "pages/index/index",
                "iconPath": "static/logo.png",
                "selectedIconPath": "static/logo.png",
                "text": "首页"
            },
            {
    
    
                "pagePath": "pages/index/todo",
                "iconPath": "static/logo.png",
                "selectedIconPath": "static/logo.png",
                "text": "待办"
            },
            {
    
    
                "pagePath": "pages/index/message",
                "iconPath": "static/logo.png",
                "selectedIconPath": "static/logo.png",
                "text": "消息"
            },
            {
    
    
                "pagePath": "pages/user/me",
                "iconPath": "static/logo.png",
                "selectedIconPath": "static/logo.png",
                "text": "个人中心"
            }
        ]
    }
}

build.js (dynamic compilation, reading, writing to generate pages.json file)

build.js is used for compiling, dynamically reading and writing to generate pages.json file

const fs = require('fs')
const path = require('path')
const router = require('./index.js')


/**
 * 加载'./modules'目录子路由配置文件
 * @returns {*[]}
 */
const getRouter = () => {
    
    
    const srcPath = path.resolve(__dirname, './modules')
    const result = fs.readdirSync(srcPath)
    let router = []
    result.forEach(file => {
    
    
        const route = require('./modules/' + file)
        router = [...router, ...buildRouter(route)]
    })
    return router
}

/**
 * 将子路由模块配置文件转化为pages.json配置文件格式
 * @param route
 * @returns {*[]}
 */
const buildRouter = route => {
    
    
    const res = []
    const {
    
    baseUrl, children} = route
    children.forEach(item => {
    
    
        let obj = {
    
    };
        item.path ? obj.path = baseUrl + item.path : null;
        item.name ? obj.name = item.name : null;
        obj = {
    
    
            ...obj,
            style: {
    
    
                navigationBarTitleText: item.text
            }
        }
        item.style ? obj.style = item.name : null;
        res.push(obj)
    })
    return res
}

/**
 * 构建 pages 并写入 pages.json 文件
 * 用两个空格缩进pages.json,如果喜欢制表符,第三个参数更换你为\t即可
 * @type {*[]}
 */
router.pages = getRouter()

fs.rename('src/pages.json', 'src/pages.json.back', err => {
    
    
    if (err) {
    
    
        console.log(err)
    } else {
    
    
        console.log("pages.json文件备份成功!")
        fs.writeFile('src/pages.json',
            JSON.stringify(router, null, '  '),
            err => {
    
    
                err ? console.error(err) : console.log('pages.json文件更新成功!')
            }
        )
    }
})

Configure package.json

Configure the package.json file, mainly to generate the page configuration file when executing the npm script command, or generate the pages.json file when starting the applet project

  "scripts": {
    
    
    "build:router": "node ./src/common/router/build.js",
    "serve": "(node ./src/common/router/build.js) & (npm run dev:mp-weixin --minimize)"
    }

Execute the test

Running the command on the command line node router/build.jswill generate a pages.json file in the project root directory

npm run build:router

> xxx-app@0.1.0 build:router
> node ./src/common/router/build.js

pages.json文件备份成功!
pages.json文件更新成功!

insert image description here

Dynamically generate pages.json file improvement

Reason for improvement

Due to the order relationship of different page configuration files of different modules in the router/modules directory, the files will be read in order and written to the pages.json file.

If the following files are read and written in order, the pages parameter configuration item in the pages.json file will configure the page configuration configured in error.js first. Usually, the first item in the pages parameter is used as the initial access page of the applet , which is dynamically generated here, you need to modify the first page configuration each time, such as changing to/index/login

insert image description here

Modify the read and write order of the build.js file

The improvement plan is very simple. It only needs to improve and control build.js to control the read and write sequence of js files configured by different modules based on the process of dynamically generating pages.json files to obtain the desired pages.json file.

const fs = require('fs')
const router = require('./index.js')

const home = require('./modules/home.js')
const error = require('./modules/error.js')
const process = require('./modules/process.js')
const user = require('./modules/user.js')

const allPageSetting = [
    home,
    error,
    process,
    user
]

/**
 * 加载'./modules'目录子路由配置文件
 * @returns {*[]}
 */
const getRouter = () => {
    
    
    let router = []
    allPageSetting.forEach(item => {
    
    
        router = [...router, ...buildRouter(item)]
    })
    return router
}

/**
 * 将子路由模块配置文件转化为pages.json配置文件格式
 * @param route
 * @returns {*[]}
 */
const buildRouter = route => {
    
    
    const res = []
    const {
    
    baseUrl, children} = route
    children.forEach(item => {
    
    
        let obj = {
    
    };
        item.path ? obj.path = baseUrl + item.path : null;
        item.name ? obj.name = item.name : null;
        obj = {
    
    
            ...obj,
            style: {
    
    
                navigationBarTitleText: item.text
            }
        }
        item.style ? obj.style = item.name : null;
        res.push(obj)
    })
    return res
}

/**
 * 构建 pages 并写入 pages.json 文件
 * 用两个空格缩进pages.json,如果喜欢制表符,第三个参数更换你为\t即可
 * @type {*[]}
 */
router.pages = getRouter()

fs.rename('src/pages.json', 'src/pages.json.back', err => {
    
    
    if (err) {
    
    
        console.log(err)
    } else {
    
    
        console.log("pages.json文件备份成功!")
        fs.writeFile('src/pages.json',
            JSON.stringify(router, null, '  '),
            err => {
    
    
                err ? console.error(err) : console.log('pages.json文件更新成功!')
            }
        )
    }
})

Execute the test

Use the improved build.js to dynamically generate the pages.json file, and get the correct and required page configuration sequence as follows.
insert image description here

Dynamically generate configuration subpackage pages.json file

reason

WeChat applets stipulate that the size of the main package cannot exceed 2M. With the advent of the 5G era, 2M is really small. Usually, a small program project can easily reach the limit of 2M, so subpackage configuration must be performed.

Since the pages.json file is already dynamically generated, of course the subpackage configuration should also be dynamically generated, so there is a solution to dynamically generate and configure the subpackage pages.json file.

Modify the build.js file

To dynamically generate the configuration subcontract pages.json file, you only need to configure the structure of the pages.json file according to the requirements of the development document to construct and generate it.

const fs = require('fs')
const router = require('./index.js')

const home = require('./modules/home.js')
const error = require('./modules/error.js')
const process = require('./modules/process.js')
const user = require('./modules/user.js')

const mainPackagesPages = [
    home,
    error,
    user
]

/**
 * 加载'./modules'目录子路由配置文件
 * @returns {*[]}
 */
const getRouter = () => {
    
    
    let router = []
    mainPackagesPages.forEach(item => {
    
    
        router = [...router, ...mainPackagesPagesBuildRouter(item)]
    })
    return router
}

const subPackagesPages = [
    process,
]

/**
 * 加载需要分包的路由配置文件
 */
const getSubPackagesRouter=()=>{
    
    
    let router = []
    subPackagesPages.forEach(item => {
    
    
        router = [...router, subPackagesBuildRouter(item)]
    })
    return router
}

/**
 * 将子路由模块配置文件转化为pages.json配置文件格式
 * @param route
 * @returns {*[]}
 */
const mainPackagesPagesBuildRouter = route => {
    
    
    const res = []
    const {
    
    baseUrl, children} = route
    children.forEach(item => {
    
    
        let obj = {
    
    };
        item.path ? obj.path = baseUrl + item.path : null;
        item.name ? obj.name = item.name : null;
        obj = {
    
    
            ...obj,
            style: {
    
    
                navigationBarTitleText: item.text
            }
        }
        item.style ? obj.style = item.name : null;
        res.push(obj)
    })
    return res
}

/**
 * 构建分包页面路由
 */
const subPackagesBuildRouter=(route)=>{
    
    
    const {
    
    baseUrl, children} = route
    const jo={
    
    
        root:baseUrl,
        pages:[]
    }
    children.forEach(item => {
    
    
        let obj = {
    
    };
        item.path ? obj.path = item.path : null;
        item.name ? obj.name = item.name : null;
        obj = {
    
    
            ...obj,
            style: {
    
    
                navigationBarTitleText: item.text
            }
        }
        item.style ? obj.style = item.name : null;
        jo.pages.push(obj)
    })

    return jo
}

/**
 * 构建 pages 并写入 pages.json 文件
 * 用两个空格缩进pages.json,或使用制表符:`\t`
 * @type {*[]}
 */
router.pages = getRouter()
router.subPackages = getSubPackagesRouter()

fs.rename('src/pages.json', 'src/pages.json.back', err => {
    
    
    if (err) {
    
    
        console.log(err)
    } else {
    
    
        console.log("pages.json文件备份成功!")
        fs.writeFile('src/pages.json',
            JSON.stringify(router, null, '\t'),
            err => {
    
    
                err ? console.error(err) : console.log('pages.json文件更新成功!')
            }
        )
    }
})

Execute the test

Make sure the pages.json file exists as the following npm script command

"scripts": {
    
    
 "build:router": "node ./src/common/router/build.js"
 }

Execute npm run build:routerthe command to generate the following configuration, and at the same time, the project test is all normal.

insert image description here

Guess you like

Origin blog.csdn.net/qq_38628046/article/details/127513349