Some of the problems that may arise when you do not use automation in your daily small program development:

  1. Branch switch, code upload, preview code generation, mindless but time-consuming operation
  2. When the code generation request comes in at the same time, it needs to wait
  3. The independent mechanism of small programs makes it impossible to control the overall process as on the Web
  4. The process by which non-developers get experience codes depends on developers

Automated process ideas

  1. Trigger a build with the instruction of a pin (this step is not yet implemented, to be added later)
  2. The node end is used as the intermediary to complete process operation
  3. Jenkins side for packaging upload preview and other time-consuming operations
  4. Call back to the Node side to beautify the original information
  5. Nailing receives node information and feeds back to users

Implementation process:

Small program automatic packaging upload

  1. Generate applets key
  2. Save the key file in the project root directory

  1. Install Taro’s built-in CI plug-innpm i @tarojs/plugin-mini-ci -D
  2. Using the Taro plugin
// /config/index.js const CIPluginOpt = { weapp: { appid: "*******************", privateKeyPath: "Private. Wx30ea7a15d8979ead. Key" / / configuration key path}, / / version number version: "1.0.0"}; const config={ ... config, plugins: [["@tarojs/plugin-mini-ci", CIPluginOpt]] }Copy the code
  1. Configuration commands
// package.json {"scripts": {// "add ":" downloadp ": "If you do something about the syndrome, try to do something about it." Taro build --type appellate --open, // If you do, try to do something about it. "Build --type reappellate --upload", // if he/she does something else, he/she will do it automatically. "Taro build --type retry --preview"}, "taroConfig": {"version": "1.0.0", "desc":" download "}Copy the code

When NPM run build: Appellate: Upload is completed, Taro’s package compilation process and results will appear. A package upload record will also appear in the background of wechat public account

There may be upload failure due to the large main package. At this time, it is suggested to subcontract. For the specific subcontract, please refer to the official website

Developers.weixin.qq.com/miniprogram…

  1. Dist file compression (since the files will be uploaded to OSS and the dist file package will be downloaded directly with the later nail, MY expectation is to upload the DIST file package and Taro’s package to OSS together)
  • Install Jszip (Jszip is a JavaScript library for creating, reading, and editing.zip files, and the API is easy to use.)
    • npm install jszip
  • compression
// zip.js const JSZip = require("jszip"); const zip = new JSZip(); const fs = require("fs"); const path = require("path"); Function readDir(zip, dirPath) {const files = fs.readdirsync (dirPath); files.forEach(fileName => { const fillPath = dirPath + "/" + fileName; const file = fs.statSync(fillPath); If (file.isdirectory ()) {const dirZip = zip.folder(fileName); readDir(dirZip, fillPath); } else {// Read each file as buffer and store it in zip. File (fileName, fs.readfilesync (fillPath)); }}); } function create(sourceDir) { readDir(zip, sourceDir); GenerateAsync ({type: "nodeBuffer ", // compression type: "DEFLATE", // compression options: {// compression level: Oss const dest = path.join(__dirname, "./dist/zip"); If (dest) {// delete the old package directory const folder_exists = fs.existssync ("./dist/zip"); if (folder_exists == true) { const dirList = fs.readdirSync("./dist/zip"); dirList.forEach(function(fileName) { fs.unlinkSync("./dist/zip/" + fileName); }); } // Create a new package directory fs.mkdirsync (dest, {recursive: true}); / / the zip disk, the content is now a buffer fs. WriteFileSync (` ${dest} / miniPrograms. Service. Zip `, content); }); } function generateZip() { const sourceDir = path.join(__dirname, "./dist"); fs.access(sourceDir, err => { if (err) { fs.mkdirSync(sourceDir); } create(sourceDir); }); } generateZip();Copy the code

– added the command “build:zip”:”node zip.js” to perform compression in package.json

  1. Oss upload
// oss.client.js const OSS = require("ali-oss"); const util = require("util"); const fs = require("fs"); const path = require("path"); const readdir = util.promisify(fs.readdir); const stat = util.promisify(fs.stat); class OssClient { constructor() { this.client = new OSS({ region: "oss-cn-hangzhou", accessKeyId: "your accessKeyId ", // process.env.ACCESSKEYID, accessKeySecret: "your accessKeySecret", // process.env.ACCESSKEYSECRET, bucket: process.env.APP_ENV === "production" ? "static" : "staticdev", // process.env.BUCKET, }); } async putStream(dir, ossDir = "/", fileName) { try { const stream = fs.createReadStream(path.resolve(dir, fileName)); return await this.client.putStream(ossDir + fileName, stream); } catch (e) { console.log(e); } } async putDir(dir, ossDir) { let files; try { files = await readdir(dir); {} the catch (e) the console. The log (` - the current directory does not exist 】 【 ${dir} - `); return undefined; } for (const i in files) { const state = await stat(`${dir}/${files[i]}`); if (state.isDirectory()) { await this.putDir(`${dir}/${files[i]}`, `${ossDir}/${files[i]}`); } else { await this.putStream(dir, `${ossDir}/`, files[i]); } } } async upload() { try { await this.putDir( path.resolve(__dirname, "dist"), `miniPrograms.service` ); } catch (e) {console.log(" please try again ", e); }}} new OssClient (). The upload (). Then (() = > {the console. The log (" upload success "); }). The catch ((error) = > {the console. The log (" upload exception ", the error); });Copy the code

Add “oss:test”:”cross-env NODE_ENV=development node oss.client.js” to package.json

  1. Writing packaging scripts
// build:test.sh git pull echo Yarn echo "Automatic upload is started" NPM run build: app-dev:upload echo "Successful upload of mini-programs" echo "start compression" NPM run build:zip echo "compression complete" NPM run Oss :test echo "Compiled successfully..."Copy the code

Automatically compile and upload files by executing the compilation script

Node interface writing

Note: This project uses egg.js

  1. The installationdingtalk-robot-sender
  2. Add a custom robot to the pin group, copy the Webhook link for later use

  1. Add an interface to service
// /app/service/DingMiniTips.ts import { Service } from 'egg'; import * as ChatBot from 'dingtalk-robot-sender'; Const robot = new ChatBot({webhook: 'your webhook',// use pin custom robot webhook link}); Export Default Class Test extends Service {public async dingTips(CTX) {const textContent = {msgType: 'actionCard', actionCard: {title: 'Automatic build of applet ', text:' Automatic build of applet completed \n\n\n Please click download to get the latest applet compressed package \n\n\n', btnOrientation: '0', BTNS: [{title: 'download ', actionURL: 'your zip address', // use zip address uploaded to OSS},],},}; robot.send(textContent).then(res => { console.log('res', res); }); }}Copy the code
  1. Introduce the new interface in controller
// /app/controller/miniAppTips.ts import { Controller } from 'egg'; export default class HomeController extends Controller { public async MiniAppTips() { const { ctx } = this; await ctx.service.dingMiniTips.dingTips(ctx); ctx.status = 200; Ctx. body = {data: null, MSG: 'build message sent successfully ',}; }}Copy the code
  1. Add this interface to router.ts
router.get('/miniAppTips', controller.miniAppTips.MiniAppTips);
Copy the code

At this stage, you can test whether the link between the pin and OSS is effective. If you request this interface in Postcode, the pin will display the corresponding card information

Click Download to download the applets and upload the DIST file package in OSS

GitLab applets project Jenkins automatically publish

For this step, refer to my previous article on the automated project and Jenkins release process (server-side Project Server Configuration Process (GitLab+Jenkins)).

The deployment process is the same, the only thing that needs to be added is that the script executed needs to add a command to trigger the robot to pin

cd /storage/node/miniPrograms.service
sh build-test.sh
curl http://*****.com/miniAppTips
Copy the code

The entire process is now complete, just click build on Jenkins or upload the change code locally to trigger Jenkins build. After executing the build-test.sh script, the small program was automatically packaged and uploaded to wechat public platform, dist files including compressed package uploaded oss. After completing all the tasks, trigger the curl command to trigger the link interface of Dingding and send the card prompt to dingding. Click “Eliminate disaster” to download the compressed package. The test engineer can test the code in wechat developer tool according to the decompressed dist file.