生成版本号配置的文件
hooks.js
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 = ref ? fs.readFileSync('.git/' + ref, 'utf-8').trim() : gitHEAD; let date = (new Date()).toISOString(); let result = ` module.exports = { version: '${version}', commitId: '${commitId}', date: '${date}', }; `; fs.writeFile('./config.js', result, 'utf8', function (err) { if (err) { console.error('write .version.js error', err) }; });
从 git 库中忽略(不跟踪)版本号文件
.gitignore
.version.js
在项目初始化时(npm install)生成版本号文件(.version.js)
package.json
{ // ... "scripts": { "preinstall": "node hooks.js" }, // ... }
在用微信开发者工具发布小程序前生成版本号文件
project.config.json
{ // ... "scripts": { "beforeCompile": "node hooks.js", "beforePreview": "node hooks.js", "beforeUpload": "node hooks.js" }, // ... }
在微信小程序中使用版本号
app.js
import * as versionConfig from './.version'; const version = versionConfig.version; const commitId = versionConfig.commitId; App({ data: { version: { name: version || '', commitId: commitId || '', }, }, });
/pages/about.js
const app = getApp(); Page({ data: { version: app.data.version.name || '-', }, });
/pages/about.wxml
<view>版本号:{{version}}</view>