javascript - 是否有办法重复抓取 `pkg.json` 版本作为变量来替换 Grunt 中 `index.js` 文件的版本?

标签 javascript gruntjs

我有一个咕噜构建。里面有grunt-bumpgrunt-replace。每次运行时,我都会使用 grunt-bumppkg.json 中升级一个版本。而且我还想在每次运行 grunt-replace 时将 index.js 版本替换为 pkg.json 版本号。但是,我不能重复执行此操作,因为一旦变量`@@package 被替换,该变量就不再存在。

Gruntfile.js:

module.exports = function(grunt) {

grunt.initconfig({
pkg: grunt.file.readjson('package.json'),

bump: {
  options: {
    files: ['package.json'],
    updateconfigs: [],
    commit: false,
    commitmessage: 'release v%version%',
    commitfiles: ['package.json'],
    createtag: false,
    tagname: 'v%version%',
    tagmessage: 'version %version%',
    push: false,
    pushto: 'upstream',
    gitdescribeoptions: '--tags --always --abbrev=1 --dirty=-d',
    globalreplace: false,
    prereleasename: false,
    metadata: '',
    regexp: false
  }
},

replace : {
  dist : {
    options : {
      patterns : [
        {
          match: 'packageJsonVersion',
          replacement: '<%= pkg.version %>';
        }
      ]
    },

    files : [
      {
        expand : true,
        flatten : true,
        src : [ 'index.html' ],
        dest : './'
      },
    ]
  }
 },
});

grunt.loadnpmtasks('grunt-bump');
grunt.loadnpmtasks('grunt-replace');

grunt.registertask('default', ['uglify']);
};

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title></title>
</head>
<body>


  <script src="index.@@packageJsonVersion.js"></script>
</body>
</html>

最佳答案

通常,我的基本 index.html 文件包含要在 src 文件夹中替换的变量,但我实际上复制该文件并在 build 文件夹(或任何实际包含您的产品静态 Assets 的文件夹)。这样,基本文件就不会被更改。
也许您可以更改dest并使您的网络服务器指向index.html的产品版本?

files : [
      {
        expand : true,
        flatten : true,
        src : [ 'index.html' ],
        dest : 'build/index.html'
      },
    ]

关于javascript - 是否有办法重复抓取 `pkg.json` 版本作为变量来替换 Grunt 中 `index.js` 文件的版本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40553712/

相关文章:

gruntjs - grunt-contrib-jshint 不会提示 console.log

css - 我在哪里可以将任何自定义 CSS 添加到 angular-fullstack 应用程序中?

javascript - 当使用 Angular 2 进行 HTTP 调用失败并出现 404 错误时,如何构建占位符对象?

javascript - html5 视频标签在 android phonegap 中不起作用

javascript - 聊天 GPT API key 故障排除

sass - grunt 说没有找到 "sass"目标

gruntjs - 从Grunt任务运行Mocha时,堆栈跟踪被隐藏

javascript - 如何检查元素是否存在?

javascript - 如何根据其属性值过滤充满数组的对象

node.js - npm/咕噜声 : is it possible to install grunt without npm?