How to quickly get started with VUE3.0: Enter learning
The picture above shows the测试环境/开发环境
version information displayed on the page. [Recommended related tutorials: "Angular Tutorial"]
There will be an introduction later.
The picture above shows the Git Commit
information of each submission. Of course, here I record every submission. You can record it every time you build.
So, let’s use Angular
to achieve the next effect. The same applies to React
and Vue
.
Because the focus here is not to build the environment, we can just use angular-cli
scaffolding to directly generate a project.
Step 1: Install the scaffolding tool
npm install -g @angular/cli
Step 2: Create a project
# ng new PROJECT_NAME ng new ng-commit
Step 3: Run the project
npm run start
The project is running. It listens to port 4200
by default. Just open http://localhost:4200/
in the browser.
Under the premise that port 4200 is not occupied
at this time, the composition of the key folder src
of the ng-commit
project is as follows:
src ├── app // Application body │ ├── app-routing.module.ts // Routing module │ . │ └── app.module.ts // Application module ├── assets // Static resources ├── main.ts // Entry file. └── style.less // The directory structure above the global style
. We will add the services
service directory in the app
directory and the version.json
file in the assets
directory later.
and create a file version.txt
in the root directory to store the submitted information; create a file commit.js
in the root directory to operate the submission information.
The focus is on commit.js
, let’s go directly to the topic:
const execSync = require('child_process').execSync; const fs = require('fs') const versionPath = 'version.txt' const buildPath = 'dist' const autoPush = true; const commit = execSync('git show -s --format=%H').toString().trim(); // Current version number let versionStr = ''; // Version string if(fs.existsSync( versionPath)) { versionStr = fs.readFileSync(versionPath).toString() + 'n'; } if(versionStr.indexOf(commit) != -1) { console.warn('x1B[33m%sx1b[0m', 'warming: The current git version data already exists!n') } else { let name = execSync('git show -s --format=%cn').toString().trim(); // name let email = execSync('git show -s --format=%ce').toString ().trim(); // Email let date = new Date(execSync('git show -s --format=%cd').toString()); // Date let message = execSync('git show -s --format=%s').toString().trim(); // Description versionStr = `git:${commit}nAuthor:${name}<${email}>nDate:${date .getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate()+' '+date.getHours()+':'+date.getMinutes()}n Description:${message}n${new Array(80).join('*')}n${versionStr}`; fs.writeFileSync(versionPath, versionStr); // After writing the version information, automatically submit the version information to git of the current branch if(autoPush) { // This step can be written according to actual needs execSync(`git add ${ versionPath }`); execSync(`git commit ${ versionPath } -m automatically submit version information`); execSync(`git push origin ${ execSync('git rev-parse --abbrev-ref HEAD').toString().trim() }`) } } if(fs.existsSync(buildPath)) { fs.writeFileSync(`${ buildPath }/${ versionPath }`, fs.readFileSync(versionPath)) }
The above files can be processed directly through node commit.js
. In order to facilitate management, we add the command line to package.json
:
"scripts": { "commit": "node commit.js" }
In this way, using npm run commit
has the same effect as node commit.js
.
With the above preparation, we can generate version information version.json
in the specified format through the commit
information.
Create a new file version.js
in the root directory to generate version data.
const execSync = require('child_process').execSync; const fs = require('fs') const targetFile = 'src/assets/version.json'; //The target file stored in const commit = execSync('git show -s --format=%h').toString().trim(); //Current Submitted version number, the first 7 digits of the hash value let date = new Date(execSync('git show -s --format=%cd').toString()); // Date let message = execSync('git show - s --format=%s').toString().trim(); // Description let versionObj = { "commit": commit, "date": date, "message": message }; const data = JSON.stringify(versionObj); fs.writeFile(targetFile, data, (err) => { if(err) { throw err } console.log('Stringify Json data is saved.') })
We add a command line to package.json
to facilitate management:
"scripts": { "version": "node version.js" }
Generate different version information for different environments. Suppose we have a development
environment, production
environment, and a test
environment.
major.minor.patch
. For example: 1.1.0major.minor.patch:beta
. For example: 1.1.0:betamajor.minor.path-data:hash
, such as: 1.1.0-2022.01.01:4rtr5rgto facilitate management of different environments. We create a new file in the root directory of the project as follows:
config ├── default.json // Configuration file called by the project ├── development.json // Development environment configuration file ├── production.json // Production environment configuration file └── test.json // Test environment configuration file
related The file content is as follows:
// development.json { "env": "development", "version": "1.3.0" }
// production.json { "env": "production", "version": "1.3.0" }
//test.json { "env": "test", "version": "1.3.0" }
default.json
copies the configuration information of different environments based on the command line, and configure it in package.json
:
"scripts": { "copyConfigProduction": "cp ./config/production.json ./config/default.json", "copyConfigDevelopment": "cp ./config/development.json ./config/default.json", "copyConfigTest": "cp ./config/test.json ./config/default.json", }
Is easy Bro, right?
Integrate the contents of generated version information to generate different version information according to different environments. The specific code is as follows:
const execSync = require('child_process').execSync; const fs = require('fs') const targetFile = 'src/assets/version.json'; // The target file stored in const config = require('./config/default.json'); const commit = execSync('git show -s --format=%h').toString().trim(); //The currently submitted version number let date = new Date(execSync('git show -s --format =%cd').toString()); // Date let message = execSync('git show -s --format=%s').toString().trim(); // Description let versionObj = { "env": config.env, "version": "", "commit": commit, "date": date, "message": message }; //Format date const formatDay = (date) => { let formatted_date = date.getFullYear() + "." + (date.getMonth()+1) + "." +date.getDate() return formatted_date; } if(config.env === 'production') { versionObj.version = config.version } if(config.env === 'development') { versionObj.version = `${ config.version }:beta` } if(config.env === 'test') { versionObj.version = `${ config.version }-${ formatDay(date) }:${ commit }` } const data = JSON.stringify(versionObj); fs.writeFile(targetFile, data, (err) => { if(err) { throw err } console.log('Stringify Json data is saved.') })
Add command lines for different environments in package.json
:
"scripts": { "build:production": "npm run copyConfigProduction && npm run version", "build:development": "npm run copyConfigDevelopment && npm run version", "build:test": "npm run copyConfigTest && npm run version", }
The generated version information will be stored directly in assets
, and the specific path is src/assets/version.json
.
The last step is to display the version information on the page. This is combined with angular
.
Use ng generate service version
to generate version
service in the app/services
directory. Add request information to the generated version.service.ts
file as follows:
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class VersionService { constructor( private http: HttpClient ) { } public getVersion():Observable<any> { return this.http.get('assets/version.json') } }
Before using the request, mount the HttpClientModule
module in the app.module.ts
file:
import { HttpClientModule } from '@angular/common/http'; // ... imports: [ HttpClientModule ],
then just call it in the component. Here is the app.component.ts
file:
import { Component } from '@angular/core'; import { VersionService } from './services/version.service'; //Introduce version service @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.less'] }) export class AppComponent { public version: string = '1.0.0' constructor( private readonly versionService: VersionService ) {} ngOnInit() { this.versionService.getVersion().subscribe({ next: (data: any) => { this.version = data.version //Change version information}, error: (error: any) => { console.error(error) } }) } }
At this point, we have completed the version information. Let's finally adjust the command of package.json
:
"scripts": { "start": "ng serve", "version": "node version.js", "commit": "node commit.js", "build": "ng build", "build:production": "npm run copyConfigProduction && npm run version && npm run build", "build:development": "npm run copyConfigDevelopment && npm run version && npm run build", "build:test": "npm run copyConfigTest && npm run version && npm run build", "copyConfigProduction": "cp ./config/production.json ./config/default.json", "copyConfigDevelopment": "cp ./config/development.json ./config/default.json", "copyConfigTest": "cp ./config/test.json ./config/default.json" }
The purpose of using scripts
is to facilitate management, but also to facilitate jenkins
construction and call. For the jenkins
part, interested parties can try it on their own.