首页 » 前端 » Vue.js » 正文

在项目中调用 package.json 里的版本号和 git 的分支、提交记录信息

发布者:站点默认
2019/03/2 浏览数(1,243) 分类:Vue.js 在项目中调用 package.json 里的版本号和 git 的分支、提交记录信息已关闭评论

在项目中调用版本号和git信息

Vue Cli 3

第一步:创建 /vue.config.js,内容如下:

const packageInfo = require('./package.json');
const fs = require('fs');
const gitHEAD = fs.readFileSync('.git/HEAD', 'utf-8').trim(); // ref: refs/heads/feature/xxx
const ref = gitHEAD.split(': ')[1]; // refs/heads/feature/xxx
const branch = gitHEAD.split('/').slice(2).join('/'); // feature/xxx
const commitId = fs.readFileSync('.git/' + ref, 'utf-8').trim().substr(0, 7);
const buildDate = new Date().toISOString(); // "2019-03-02T02:16:34.149Z"
module.exports = {
  chainWebpack: config => {
    config.plugin('html').tap(args => {
      args[0].AppInfo = {
        name: packageInfo.name,
        version: packageInfo.version,
        branch,
        commitId,
        budilDate
      };
      return args;
    });
  }
};

第二步:编辑 /public/index.html,在需要放置版本信息的地方参照以下方式编写(文末有完整版index.html):

<div>版本号:<%=htmlWebpackPlugin.options.AppInfo.version%></div>
或:
<script>
try {
  var AppInfo = JSON.parse('<%=JSON.stringify(htmlWebpackPlugin.options.AppInfo)%>');
  console.group('Project Info:');
  console.log('%c' +
    '    Name: ' + AppInfo.name     + '\n' +
    ' Version: ' + AppInfo.version  + '\n' +
    '  Branch: ' + AppInfo.branch   + '\n' +
    'CommitId: ' + AppInfo.commitId + '\n' +
    '   Build: ' + new Date(AppInfo.buildDate).toLocaleString(),
    'color:#C00'
    );
  console.groupEnd();
} catch(e) {}
</script>

第三步:重新运行 yarn server 查看效果。

Vue Cli 2

第一步:编辑 /config/prod.env.js 修改为:

'use strict';
const packageInfo = require('../package.json');
const fs = require('fs');
const gitHEAD = fs.readFileSync('.git/HEAD', 'utf-8').trim();
const ref = gitHEAD.split(': ')[1];
const branch = gitHEAD.split('/').slice(2).join('/');
const commitId = fs.readFileSync('.git/' + ref, 'utf-8').trim();
const buildDate = new Date().toISOString();
module.exports = {
  APP_INFO: JSON.stringify({
    name: packageInfo.name,
    version: packageInfo.version,
    branch,
    commitId,
    buildDate
  }),
  NODE_ENV: '"production"'
};

dev.env.js 会在 prod.env.js 的基础上修改所以不用管 dev.env.js

第二步:编辑 /build/webpack.prod.conf.js 和 /build/webpack.dev.conf.js 参照以下代码修改:

// build/webpack.prod.conf.js
// ...
plugins: [
  // ...
  new HtmlWebpackPlugin({
    appinfo: JSON.parse(env.APP_INFO), // 添加这行
    filename: process.env.NODE_ENV === 'testing' ? 'index.html' : config.build.index,
    template: 'index.html',
    favicon: 'static/favicon.ico',
    inject: true,
    // ...
  }),
  // ...
]
// ...
// build/webpack.dev.conf.js
const env = require('../config/dev.env');  // 添加这行(另有一行代码也引了这个文件,那行可以用 env 变量代替掉 require)
plugins: [
  // ...
  new HtmlWebpackPlugin({
    appinfo: JSON.parse(env.APP_INFO), // 添加这行
    filename: 'index.html',
    template: 'index.html',
    favicon: 'static/favicon.ico',
    inject: true
  }),
  // ...
]
// ...

第三步:编辑 /index.html,在需要放置版本信息的地方参照以下方式编写(文末有完整版index.html):

<div>版本号:<%=htmlWebpackPlugin.options.appinfo.version%></div>
或:
<script>
try {
  var appinfo = JSON.parse('<%=JSON.stringify(htmlWebpackPlugin.options.appinfo)%>');
  console.group('Project Info:');
  console.log('%c' +
    '    Name: ' + appinfo.name     + '\n' +
    ' Version: ' + appinfo.version  + '\n' +
    '  Branch: ' + appinfo.branch   + '\n' +
    'CommitId: ' + appinfo.commitId + '\n' +
    '   Build: ' + new Date(appinfo.buildDate).toLocaleString(),
    'color:#C00'
    );
  console.groupEnd();
} catch(e) {}
</script>

第四步:重新运行 npm start 查看效果。

在项目里使用

1.在入口 index.html 使用:

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title></title>
  <script>
    try {
      var appinfo = JSON.parse('<%=JSON.stringify(htmlWebpackPlugin.options.appinfo)%>');
      console.group('Project Info:');
      console.log('%c' +
        '    Name: ' + appinfo.name     + '\n' +
        ' Version: ' + appinfo.version  + '\n' +
        '  Branch: ' + appinfo.branch   + '\n' +
        'CommitId: ' + appinfo.commitId + '\n' +
        '   Build: ' + new Date(appinfo.buildDate).toLocaleString(),
        'color:#C00'
        );
      console.groupEnd();
    } catch(e) {}
  </script>
</head>
<body>
  <div id="app"></div>
  <!-- built files will be auto injected -->
</body>
</html>

2.在 vue 文件里使用:

<template />

<script>
export default {
  methods: {
    showAbout() {
      let self = this;
      let content = `Ver${process.env.AppInfo.version}`; // 直接用
      content += ' Build ' + new Date().getTime();
      self.$vux.alert.show({
        title: '关于',
        content
      });
    }
  }
};
</script>

<style lang="stylus" scoped />
点击返回顶部
  1. 留言
  2. 联系方式