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

How to dynamically change the version from package.json?

  1. 我从服务器
  2. 获取版本 1.0.1 (server_version)
  3. 我比较一下process.env.version中的内容===server_version
  4. 如果是这样,那我改process.env.version = server_version.

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

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

如果您正在使用 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();
        });
      },
    }
};