const packageInfo = require('./package.json'); const fs = require('fs'); const gitHEAD = fs.readFileSync('.git/HEAD', 'utf-8').trim(); const ref = gitHEAD.split(': ')[1]; let version = packageInfo.version; let commitId = ''; if (ref) { commitId = fs.readFileSync('.git/' + ref, 'utf-8').trim(); } else { commitId = gitHEAD; } console.log(version, commitId); fs.readFile('./config.js', 'utf8', function (err, content) { var result = content; result = result.replace(/const version = '.*?';/g, `const version = '${version}';`); result = result.replace(/const commitId = '.*?';/g, `const commitId = '${commitId}';`); console.log(result); fs.writeFile('./config.js', result, 'utf8', function (err) { if (err) { console.log(err) }; }); })
const p = require('./package.json'); const f = require('fs'); const g = f.readFileSync('.git/HEAD', 'utf-8').trim(); const r = g.split(': ')[1]; const v = p.version; const i = r ? f.readFileSync('.git/' + r, 'utf-8').trim() : g; f.readFile('./config.js', 'utf8', function (err, c) { c = c.replace(/const version = '.*?';/g, `const version = '${v}';`); c = c.replace(/const commitId = '.*?';/g, `const commitId = '${i}';`); f.writeFile('./config.js', c, 'utf8', () => {}); });
示例
vue.config.js
const { DefinePlugin } = require('webpack'); 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(); const budilDate = new Date().toISOString(); // "2019-03-02T02:16:34.149Z" const appInfo = { name: packageInfo.name_cn || packageInfo.name, version: `v${packageInfo.version}`, branch, beta: branch !== 'master', build: commitId, date: budilDate, }; module.exports = { chainWebpack: config => { // 在入口文件中添加版本信息 /public/index.html, usage: <%=htmlWebpackPlugin.options.appInfo.name%> config.plugin('html').tap(args => { args[0].appInfo = appInfo; return args; }); // 在 vue 项目中使用版本信息 /src/view/*.vue, usage: {{ process.env.appInfo.name }} config.plugin('define-env').use(DefinePlugin, [ { 'process.env.appInfo': JSON.stringify(appInfo), }, ]); }, devServer: { hot: true, proxy: { '/api': { target: process.env.VUE_APP_API_SERVER_URL, // see .env changeOrigin: true, pathRewrite: { // '^/api': '' // 把二级目录变成一级目录 }, }, '/storage': { target: process.env.VUE_APP_API_SERVER_URL, // see .env changeOrigin: true, pathRewrite: { // '^/storage': '' // 把二级目录变成一级目录 }, }, }, }, };