我通过调试uniapp源代码,找到微信打包读取manifest.json关键位置

@dcloudio/webpack-uni-pages-loader/index-new.js

@dcloudio/webpack-uni-pages-loader/platforms/mp.js

但是在整个编译过程中你无法修改其中的值。

我也想过去github上修改源代码提交,但是在issue中看到了开发人员说他不想这么做(能做但是不做比不会做更可怕 0.0 )

所以只能换个思路

通过webpack钩子,在项目编译完成后修改输出目录里的结果

所幸的是开发人员在process中把项目里的该用的路径配置都写进去了。

所以开始整活吧

const { getManifestJson, getPagesJson } = require('@dcloudio/uni-cli-shared/lib')
const { getPlatformProject } = require('@dcloudio/uni-cli-shared/lib/platform')
const merge = require('webpack-merge')
const fs = require('fs')
const path = require('path')

class JLWebpackPlugin {
    constructor(options) {
        this.options = options;
    }

    apply(compiler) {
        if (process.env.UNI_PLATFORM === 'h5') return;

        compiler.hooks.afterEmit.tap('JLWebpackPlugin', (compilation, cb) => {
            console.log('JLWebpackPlugin compiler.hooks');

            const jsonFiles = require('@dcloudio/webpack-uni-pages-loader/lib/platforms/' + process.env.UNI_PLATFORM)(getPagesJson(), getManifestJson(), false);

            let project = jsonFiles.filter(item => (item.name + '.json') === getPlatformProject())[0]
            if (!project) return

            const appid = process.env.VUE_APP_MP_APPID || 'touristappid'
            project = merge(project, { content: { appid: appid } })

            fs.writeFileSync(path.resolve(process.env.UNI_OUTPUT_DIR, getPlatformProject()), JSON.stringify(project.content, null, 2))
        });
    }
}

module.exports = JLWebpackPlugin;

然后将自己写好的WebpackPlugin添加到 vue.config.js 中

const TransformPages = require('uni-read-pages')
const JLWebpackPlugin = require('./jl-webpack-plugin')
const { webpack } = new TransformPages()

module.exports = {
    configureWebpack: {
        plugins: [
            new webpack.DefinePlugin({
                ROUTES: webpack.DefinePlugin.runtimeValue(() => {
                    const tfPages = new TransformPages({
                        includes: ['path', 'name', 'aliasPath', 'animation']
                    });
                    return JSON.stringify(tfPages.routes)
                }, true)
            }),
            new JLWebpackPlugin()
        ]
    },
    css: {
        loaderOptions: {
            sass: {
                implementation: require("sass"),
            }
        }
    }
}

因为我定义了一个 env 变量  VUE_APP_MP_APPID 

所以在对应项目的 .env.xxxx 里添加即可(vue-cli的env,请自行查阅@vue/cli官方文档)

结尾吐槽:uniapp源码中写了很多的 process 环境变量,可以通过启动命令修改 配置达到各种目的,比如输出目录修改之类的(我经常使用cordova打包,需要根目录输出www文件夹),但是官方文档中从未提起。

更多推荐