Ionic 3 生产环境下带版本号的构建

11
当我构建Ionic桌面项目时,我使用以下命令:

ionic cordova build browser --prod

这会生成以下文件:

build/main.js

但我想在构建过程中自动向生成的文件添加版本号,以便每次生产构建后无需清除浏览器缓存。希望最终得到类似于以下形式的结果:

build/main.js?version=1.00

是否有相关标志可用,还是必须手动完成?任何建议都将不胜感激! 编辑: 我的解决方案已经上传至GitHub供有兴趣的人参考! https://github.com/RichardM99/ionic-3-version-build-file-hook
2个回答

4
这里有一些建议-你可以创建一个cordova钩子。
钩子是您希望在不同的构建过程阶段执行的脚本。在您的情况下,您正在查看一个脚本,在构建事件完成后重命名main.js文件,或者换句话说,是'after_build'类型的钩子。
该脚本通常是一个Node.js文件,尽管您也可以执行其他类型的脚本。
还有一件事。由于您想绕过缓存,所以您不会重命名文件本身。相反,您将想要替换“index.html”中对“main.js”的引用,以包括随机或可能是实际版本号。
我已经指出了方向,但不会过度解释。查找有关cordova hooks的文档。如果您了解Javascript / Node,它们非常简单。
像这样的东西应该能够完成任务:
var index_orig = fs.readFileSync(path-to-index.html, 'utf8');
var index_new = index_orig.replace("main.js", "main.js?version="+version_num);
fs.writeFileSync(path-to-index.html, index_new, 'utf8');

如果您想要实际的构建编号,可以读取您的config.xml并解析它以获取其值。
希望这有所帮助。

1
非常感谢您,先生。 - user2085143

4

很久以前我写了一篇博客

在我的构建流程中,我有一个命令来设置版本号。

version "$(app.versionPrefix)$(Build.BuildNumber)"

$(app.versionPrefix) - 是前缀版本,例如0.1。

$(Build.BuildNumber) - 是构建版本。

然后我有环境文件。

export const environment = {
    apiUrl: 'https://....',
    production: true,
    version: '0.0.57'                                     
}

然后我有一个JavaScript脚本来更新环境和config.xml中的版本号。

var replace = require('replace-in-file');
var package = require("./package.json");
var buildVersion = package.version;
const options = {
    files: ['config.xml'],
    from: /" version="([0-9]*.[0-9]*.[0-9]*)"/g,
    to: "\" version=\""+ buildVersion + "\"",
    allowEmptyPaths: false,
};

const optionsEnv = {
     files: ['src/environments/environment.prod.ts'],
    from: /version: '(.*)'/g,
    to: "version: '"+ buildVersion + "' ",
    allowEmptyPaths: false,
};

try {
    let changedFiles = replace.sync(options);
    if (changedFiles == 0) {
        throw "Please make sure that file '" + options.files + "' has \"version: ''\"";
    }
    changedFiles = replace.sync(optionsEnv);
    if (changedFiles == 0) {
        throw "Please make sure that file '" + optionsEnv.files + "' has \"version: ''\"";
    }
    console.log('Build version set: "' + options.to + '"');
}
catch (error) {
    console.error('Error occurred:', error);
    throw error
}

注意:你需要安装插件replace-in-file

然后在构建管道中运行以下脚本:

node ./replace.build.js

在您的情况下,如果只需要浏览器,则可以调整脚本。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接