如何动态更改package.json的版本?

发布于 2025-01-10 11:29:50 字数 249 浏览 0 评论 0原文

  1. 我从服务器获取版本 1.0.1 (server_version)
  2. 我比较 process.env.version === server_version 中的内容
  3. 如果是这种情况,那么我更改 process.env.version = server_version。

但是,我无法从客户端做到这一点。

所有这些都需要向用户请求更新,即当有新版本发布时,然后询问,然后执行 $router.go()

  1. I get version 1.0.1 (server_version) from the server
  2. I compare what is in process.env.version === server_version
  3. If this is the case, then I change process.env.version = server_version.

However, I just can't do it from the client side.

All this is needed to request an update from the user, that is, when a new version is released, then ask, and then do $router.go()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

大姐,你呐 2025-01-17 11:29:50

如果您使用的是 Vue-CLI - 您可以像我一样执行以下操作:

// vue.config.js
module.exports =
{
  chainWebpack: config =>
  {
    config.plugin('define')
      .tap(args =>
      {
        args[0]['process.env'].BUILD_TIME = webpack.DefinePlugin.runtimeValue(Date.now, ['./package.json']);
        args[0]['process.env'].VERSION = JSON.stringify(pk.version);
        return args;
      });
    return config;
  }
}

然后,在您的 public/index.html

<!DOCTYPE html>
<html>
  <head> 
  .....
    <template id="VERSION"><%= process.env.VERSION %></template> 
  .....
</html>

然后,在您的 src/main.js

import mixinVersion from './mixins/mixinVersion'
import { version } from '../package.json'

.....

new Vue({
  mixins: [mixinVersion],
  computed:
  {
      appVersion()
      {
        const buildTime = new Date(process.env.BUILD_TIME);
        return version + ' (' + buildTime.toLocaleString('en', {
          year: 'numeric',
          day: 'numeric',
          month: 'short',
          hour: 'numeric',
          minute: 'numeric',
        }) + ')';
      },
  },
  created()
  {
    this.firstVersionCheck();
  }
});

然后在 src/mixins/mixinVersion.js 中

import { version } from '@/../package.json';

const checkingPeriod = 200; // in seconds

function isNewerVersion(_old, _new)
{
  // return true if SemVersion A is newer than B
  const oldVer = _old.split('.');
  const newVer = _new.split('.');
  if (+oldVer[0] < +newVer[0]) return false;
  if (+oldVer[0] > +newVer[0]) return true;
  if (+oldVer[1] < +newVer[1]) return false;
  if (+oldVer[1] > +newVer[1]) return true;
  return +oldVer[2] > +newVer[2];
}

export default
{
  data()
  {
    return {
      newVersionExists: false,
      timerVersion: null,
      lastVersionCheck: null,
      windowHiddenProp: '',
    };
  },
  watch:
    {
      newVersionExists(newVal, oldVal)
      {
        // if the user decides to dismiss and not refresh - we must continue checking
        if (oldVal && !newVal) this.scheduleVersion();
      },
    },
  methods:
    {
      firstVersionCheck()
      {
        this.lastVersionCheck = Date.now();
        // Set the name of the hidden property and the change event for visibility
        let visibilityChange;
        if (typeof document.hidden !== 'undefined')
        {
          // Opera 12.10 and Firefox 18 and later support
          this.windowHiddenProp = 'hidden';
          visibilityChange = 'visibilitychange';
        }
        else if (typeof document.msHidden !== 'undefined')
        {
          this.windowHiddenProp = 'msHidden';
          visibilityChange = 'msvisibilitychange';
        }
        else if (typeof document.webkitHidden !== 'undefined')
        {
          this.windowHiddenProp = 'webkitHidden';
          visibilityChange = 'webkitvisibilitychange';
        }
        document.addEventListener(visibilityChange, this.handlePageVisibility, false);
        this.scheduleVersion();
      },
      handlePageVisibility()
      {
        if (!document[this.windowHiddenProp])
        {
          // if too much time has passed in the background - immediately check for new version
          if (Date.now() - this.lastVersionCheck > checkingPeriod * 1000)
          {
            if (this.timerVersion) clearTimeout(this.timerVersion);
            this.checkVersion();
          }
        }
      },
      scheduleVersion()
      {
        // check for new versions
        if (this.timerVersion) clearTimeout(this.timerVersion);
        this.timerVersion = setTimeout(this.checkVersion, checkingPeriod * 1000); // check for new version every 3.3 minutes
      },
      checkVersion()
      {
        this.timerVersion = null;
        fetch(process.env.BASE_URL + 'index.html', {
          headers:
            {
              'X-SRS-Version': version,
            }
        }).then(response =>
        {
          if (response.status != 200) throw new Error('HTTP status = ' + response.status);
          return response.text();
        }).then(t =>
        {
          this.lastVersionCheck = Date.now();
          const newVersion = t.match(/<template id="?VERSION"?>([^<]+)<\/template>/);
          if (newVersion && newVersion[1])
          {
            if (isNewerVersion(newVersion[1], version))
            {
              if (!this.newVersionExists) // do not show multiple notifications
              {
                this.$snotify.confirm('There is a new version', 'New version', {
                  timeout: 0,
                  closeOnClick: false,
                  position: 'leftBottom',
                  buttons:
                    [
                      {
                        text: 'REFRESH',
                        action()
                        {
                          window.location.reload();
                        }
                      }
                    ]
                });
              }
              this.newVersionExists = true;
            }
            else this.scheduleVersion();
          }
          else this.scheduleVersion();
        }).catch(err =>
        {
          if (navigator.onLine) console.error('Could not check for new version', err.message || err);
          this.scheduleVersion();
        });
      },
    }
}; 

If you're using Vue-CLI - you can do the same as me:

// vue.config.js
module.exports =
{
  chainWebpack: config =>
  {
    config.plugin('define')
      .tap(args =>
      {
        args[0]['process.env'].BUILD_TIME = webpack.DefinePlugin.runtimeValue(Date.now, ['./package.json']);
        args[0]['process.env'].VERSION = JSON.stringify(pk.version);
        return args;
      });
    return config;
  }
}

Then, in your public/index.html

<!DOCTYPE html>
<html>
  <head> 
  .....
    <template id="VERSION"><%= process.env.VERSION %></template> 
  .....
</html>

Then, in your src/main.js

import mixinVersion from './mixins/mixinVersion'
import { version } from '../package.json'

.....

new Vue({
  mixins: [mixinVersion],
  computed:
  {
      appVersion()
      {
        const buildTime = new Date(process.env.BUILD_TIME);
        return version + ' (' + buildTime.toLocaleString('en', {
          year: 'numeric',
          day: 'numeric',
          month: 'short',
          hour: 'numeric',
          minute: 'numeric',
        }) + ')';
      },
  },
  created()
  {
    this.firstVersionCheck();
  }
});

Then in src/mixins/mixinVersion.js

import { version } from '@/../package.json';

const checkingPeriod = 200; // in seconds

function isNewerVersion(_old, _new)
{
  // return true if SemVersion A is newer than B
  const oldVer = _old.split('.');
  const newVer = _new.split('.');
  if (+oldVer[0] < +newVer[0]) return false;
  if (+oldVer[0] > +newVer[0]) return true;
  if (+oldVer[1] < +newVer[1]) return false;
  if (+oldVer[1] > +newVer[1]) return true;
  return +oldVer[2] > +newVer[2];
}

export default
{
  data()
  {
    return {
      newVersionExists: false,
      timerVersion: null,
      lastVersionCheck: null,
      windowHiddenProp: '',
    };
  },
  watch:
    {
      newVersionExists(newVal, oldVal)
      {
        // if the user decides to dismiss and not refresh - we must continue checking
        if (oldVal && !newVal) this.scheduleVersion();
      },
    },
  methods:
    {
      firstVersionCheck()
      {
        this.lastVersionCheck = Date.now();
        // Set the name of the hidden property and the change event for visibility
        let visibilityChange;
        if (typeof document.hidden !== 'undefined')
        {
          // Opera 12.10 and Firefox 18 and later support
          this.windowHiddenProp = 'hidden';
          visibilityChange = 'visibilitychange';
        }
        else if (typeof document.msHidden !== 'undefined')
        {
          this.windowHiddenProp = 'msHidden';
          visibilityChange = 'msvisibilitychange';
        }
        else if (typeof document.webkitHidden !== 'undefined')
        {
          this.windowHiddenProp = 'webkitHidden';
          visibilityChange = 'webkitvisibilitychange';
        }
        document.addEventListener(visibilityChange, this.handlePageVisibility, false);
        this.scheduleVersion();
      },
      handlePageVisibility()
      {
        if (!document[this.windowHiddenProp])
        {
          // if too much time has passed in the background - immediately check for new version
          if (Date.now() - this.lastVersionCheck > checkingPeriod * 1000)
          {
            if (this.timerVersion) clearTimeout(this.timerVersion);
            this.checkVersion();
          }
        }
      },
      scheduleVersion()
      {
        // check for new versions
        if (this.timerVersion) clearTimeout(this.timerVersion);
        this.timerVersion = setTimeout(this.checkVersion, checkingPeriod * 1000); // check for new version every 3.3 minutes
      },
      checkVersion()
      {
        this.timerVersion = null;
        fetch(process.env.BASE_URL + 'index.html', {
          headers:
            {
              'X-SRS-Version': version,
            }
        }).then(response =>
        {
          if (response.status != 200) throw new Error('HTTP status = ' + response.status);
          return response.text();
        }).then(t =>
        {
          this.lastVersionCheck = Date.now();
          const newVersion = t.match(/<template id="?VERSION"?>([^<]+)<\/template>/);
          if (newVersion && newVersion[1])
          {
            if (isNewerVersion(newVersion[1], version))
            {
              if (!this.newVersionExists) // do not show multiple notifications
              {
                this.$snotify.confirm('There is a new version', 'New version', {
                  timeout: 0,
                  closeOnClick: false,
                  position: 'leftBottom',
                  buttons:
                    [
                      {
                        text: 'REFRESH',
                        action()
                        {
                          window.location.reload();
                        }
                      }
                    ]
                });
              }
              this.newVersionExists = true;
            }
            else this.scheduleVersion();
          }
          else this.scheduleVersion();
        }).catch(err =>
        {
          if (navigator.onLine) console.error('Could not check for new version', err.message || err);
          this.scheduleVersion();
        });
      },
    }
}; 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文