Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to publish WeChat Mini Programs in vscode

2025-04-08 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces how to release WeChat Mini Programs in vscode. The content is very detailed. Interested friends can use it for reference. I hope it will be helpful to you.

Analysis and disassembly

Ok, now that we have a clear understanding of the process, what capabilities do we need to analyze and analyze the whole process with the rigorous attitude of programmers? Next, we only do some analysis and disassembly of the key parts of each link, not the overall structure and code analysis of the Vscode plug-in code.

Front work

Git capability-switching Branch

Git capability-Save current branch

Vscode plug-in window capability-enter description, drop-down box select

Git capability-pull Branch

Select build branch, version and fill in the description

Temporarily save current branch changes

Switch to the target branch

Local build

Git invocation capability-use Git to undo modified files

Shell invocation capability-execute build commands

Shell invocation capability-modify file content to inject AppID

Wechat development platform api capability-get the list of recent templates for the current AppID

Automatically generate version number

Inject target Mini Program AppID

Run the uni-app build command

Undo the release of a temporary modification file

Deploy Mini Program

Dubbo capability-since the Wechat development platform accessToken capability already exists in the backend, call and obtain it directly.

Api capabilities of Wechat development platform

Ability to invoke Wechat development tools

Upload draft box on cloud

Move to template Library

Deployment Preview

The window capability of the Vscode plug-in is provided by default and does not need to be implemented, so Shell call, Git call, Dubbo call, Wechat development platform api call, Wechat development tool call need to be implemented.

Then classified, in fact, Git calls and Wechat development tool calls are command line calls, that is, Shell calls. Wechat development platform api calls are essentially http requests, but the most important accessKey is directly called Zhengzaiyun backend Dubbo API to obtain, so you need Dubbo. Let's take a look at how to do it.

The call of Shell

When you hear that Shell chrysanthemums are tight, people who are not familiar with them think that God is very complicated. In fact, they use child_process to start a sub-process, and then you can have fun. So we encapsulated a shell.ts in the project to do all the execution actions of the Shell script. If you are not familiar with child_process, please move here.

/ / part of the core code of shell.ts import {execFile, ExecFileOptions} from "child_process"; export namespace Shell {/ / directly calls the execution file of git in shell to execute the original command export async function exec (args: any [], options: ExecFileOptions = {}): Promise {const {stdin, stdinEncoding, execFileNameOrPath,... opts}: any = {maxBuffer: 1024 * 1024,... options,} Return new Promise ((resolve, reject) = > {if (! execFileNameOrPath) {reject ('error');} try {const proc = execFile (execFileNameOrPath, args, opts, (error: any | null, stdout, stderr) = > {if (error! = null) {reject (error); return } resolve (stdout as TOut);}); if (stdin! = = null) {proc.stdin?.end (stdin, stdinEncoding?? "utf8");}} catch (e) {return});}}

Then you can pass in parameters through the Shell.exec method and call them directly.

The call of Git

With the previous Shell as the basis, we can dry the call to Git. In Shell, the first parameter is the command execution file, so we need to get the address of the current Git execution file as the first parameter, followed by the splicing of normal Git commands is enough. So how do you know the path to the current Git execution file?

Get extensions.getExtension ("vscode.git") through the Git capability integrated in the Vscode plug-in, as follows

/ / get the GitApi static async getBuiltInGitApi () built into Vscode: Promise {try {const extension = extensions.getExtension ("vscode.git") as Extension

< GitExtension >

; if (extension! = = null) {const gitExtension = extension.isActive? Extension.exports: await extension.activate (); return gitExtension.getAPI (1);} catch {} return undefined;}

In the returned object, gitApi.git.path is the path to the execution file of Git. In order to make the call more convenient, we also encapsulate a git.ts as the most core and basic call to Git.

/ part of the core code of git.ts export namespace Git {export namespace Core {/ / directly calls the execution file of git in shell to execute the original command export async function exec (args: any [], options: GitExecOptions = {}): Promise {options.execFileNameOrPath = gitInfo.execPath | | "; args.splice (0,0,"-c "," core.quotepath=false ","-c "," color.ui=false ") If (process.platform = = "win32") {args.splice (0,0, "- c", "core.longpaths=true");} return Shell.exec (args, options);}}

On the outside, we directly use the Git.Core.exec method to execute the corresponding Git command.

Wechat development tools call

First of all, we need to check the developer tool settings: you need to open the service port in the developer tool settings-> security settings. So that we can directly evoke developers and do what we have to do.

In addition, we need to know the address of the execution file of the Wechat developer tool. For more information, please move the document.

MacOS: / Contents/MacOS/cli

Windows: / cli.bat

Normally Mac address / Applications/wechatwebdevtools.app/Contents/MacOS/cli

Finally, it is done through the ability to execute Shell commands provided by us before. Isn't it easy. We also encapsulated miniProgram.ts to do this.

/ / miniProgram.ts core code import {ExecFileOptions} from "child_process"; import * as vscode from "vscode"; import {Shell} from'.. / shell';interface MiniProgramExecOptions extends ExecFileOptions {branchName: string; execFileNameOrPath: string ProjectPath: string, userVersion: string, userDesc: string} export namespace MiniProgram {export namespace Core {/ / directly call git's execution file in shell to execute the original command export async function exec (args: any [], options: MiniProgramExecOptions): Promise {vscode; options.execFileNameOrPath = "/ Applications/wechatwebdevtools.app/Contents/MacOS/cli"; return Shell.exec (args, options);}} Duddo call

Although I don't understand, I think it's very powerful. I can't adjust Dubbo directly. In fact, it's very simple. I can do it with a library of nodeJs, node-zookeeper-dubbo and js-to-java. It's just that some configuration is troublesome, so I'll post the code roughly.

Const nzd = require ("node-zookeeper-dubbo"); const j2j = require ("js-to-java"); export interface DubboInstance {mp: {getComponentToken: Function;};} export class DubboService {private _ dubbo: DubboInstance; public get dubbo (): DubboInstance {return this._dubbo } constructor () {const options = {application: "your project name", / / project name register: "your server address", / / zookeeper server address, separated by commas among multiple servers dubboVer: "your version", / / dubbo version Ask the backend to know that it is 2.3.5 root: 'your root node', / / register the name of the root node on the zookeeper dependencies: {/ / dependent dubbo service set, that is, the configuration set of the service you want to invoke mp: {/ / service identity, custom According to your preference interface: "your backend dubbo service address", / / backend dubbo service address version: "your service version number", / / service version number timeout: "30000", / / timeout group: "your grouping" The / / grouping function also does not use the signature of the method exposed in the methodSignature: {/ / service You can omit getComponentToken: () = > () = > [],}, java: J2J, / / use the js-to-java library to simplify the writing of values passed to the java backend} This._dubbo = new nzd (options);}}

So far, some basic capabilities have been encapsulated.

Shell:Shell.exec method

Git:Git.Core.exec method

Wechat development tool: MiniProgram.Core.exec method

Dubbo: DobboService.dubbo.mp method

Start the front job.

Because we are going to build an advance version, it is very likely that the branch we need to build is not the branch we are currently working on, so this step is more about doing some preparatory work before building. We can't accidentally lose our own local hard-working things just because people want a preview beta version for testing.

According to the process, let's first break down the general technical actions.

Temporarily save current branch changes

Gets the current branch.

If nothing is done in the current branch, otherwise under stash

Switch to the branch you need to publish

Switch the next branch

To simplify again: get the current branch-- > Save changes-- > switch branches. It's all Git's moves. So how do you start your own Git performance in nodeJs? One key point: the invocation of Shell scripts and commands, so the essence here is to call Shell. We have implemented the basic capabilities of Shell and Git in the previous chapter, so we can just call them.

Use symbolic-ref to get the current branch

In fact, there are two kinds of Git commands.

High level Command (porcelain commands)

Underlying command (plumbing commands)

Common commands are familiar to everyone, such as branch, init, add, commit and so on. What the hell is the underlying command? in fact, the essence of all high-level commands is to call the underlying commands, which can be compared to the high-level languages such as Java,C#,Js at the language level. His underlying level is to use C or C++ is a concept. If you are interested, please move.

What can the symbolic-ref command do?

Given a parameter, read the symbol ref reference given in the branch header and output its path relative to the .git / directory. Typically, HEAD provides the branch where your work tree is located as parameters.

With the above git.ts support basic capabilities, now we are much simpler, Git.Core.exec (["symbolic-ref", "--short", "HEAD"], options)

Add basic command methods to git.ts

/ / git.ts partial code export function symbolicRef (options: GitExecOptions = {}) {return Core.exec (["symbolic-ref", "- short", "HEAD"], options);}

Implementation of getCurrentBranch method in gitService

/ / gitService.ts partial code public async getCurrentBranch (filePath: string): Promise {const branchName = await Git.Cmd.symbolicRef ({cwd: filePath}); return branchName.replace (/\ nAccord g, "");} Save changes and switch branches

When we get the current branch, compare it with our target branch and skip this step if it is consistent, otherwise we need to save and switch the current branch.

To facilitate saving and switching, we directly use Git's stash and checkout commands, and encapsulate two methods.

/ / git.ts partial code export function checkout (options: GitExecOptions = {}) {const params = ["checkout"]; if (options.branchName) {params.push (options.branchName);} else if (options.fileName) {params.push ('-', options.fileName);} return Core.exec (params, options) } export function stash (options: GitExecOptions = {}) {const params = ["stash"]; if (options.stashPop) {params.push ('pop');} return Core.exec (params, options);} Local build

Continue to analyze the basic process of locally built

It is roughly divided into the following steps

Automatically generate version number

Get the version number of current AppID in Wechat template library.

Inject Mini Program AppID that needs to be released

You need to modify the AppID in the src/manifest.json file to facilitate the upload and use of development tools

Run the uni-app build command

Run uniapp command

Undo temporary file changes at the time of release

Undo file modification

As far as ability is concerned, there are several.

Wechat api call

Ability to read and modify files

Shell command execution capability

Undo file modification ability

First of all, how to call Wechat's api? at that time, our dear back-end classmates had already done away with the Wechat token authentication ability, so we can just connect to the Wechat authentication ability in the backend. But how to get it is also a problem. Although people already have a restful interface that can be used, all interfaces have to be logged in, ah. It is not safe for people to make an anonymous reality for this small need of mine. If you think about it over and over again, then don't use restful, just transfer the Dobbo service provided by him directly. Perfect.

Get Wechat accessToken

We need to get the accessToken before we can get the Wechat api call.

So we will first use a public method to get the current accessToken, and then request Wechat development platform api.

/ / miniProgramService.ts partial code public async retrieveWxToken (): Promise {if (! Launcher.dobboService.dubbo.mp) {throw new Error ("dubbo initialization error");} const {success: dobboSuccess, error, result: wxToken,} = await Launcher.dobboService.dubbo.mp.getComponentToken (); if (! dobboSuccess) {throw new Error (`dubbo call failed: ${error} `) } console.log ("wxToken:", wxToken); return wxToken;}

If your backend does not have the authentication capability to support the Wechat development platform, you need to use nodejs to implement it. For specific Wechat open platform copywriting, please move.

Wechat open platform api calls

In fact, the Wechat open platform api call is a normal http call.

Wechat provides a series of methods, which have the following interfaces for our scenario

GetTemplateList gets the list of templates

POST https://api.weixin.qq.com/wxa/gettemplatelist?access_token==ACCESS_TOKEN

Addtotemplate moves drafts to template library

POST https://api.weixin.qq.com/wxa/gettemplatelist?access_token=ACCESS_TOKEN

DeleteTemplate deletes the specified template

POST https://api.weixin.qq.com/wxa/deletetemplate?access_token=ACCESS_TOKEN

GetTemplateDraftList gets the list of draft boxes

Https://api.weixin.qq.com/wxa/gettemplatedraftlist?access_token=ACCESS_TOKEN

For specific Wechat open platform copywriting, please move.

The automatic generation of the version number is mainly through letting the user choose the release version as "large version", "function iteration" or "patch fix" when you click on the release, and get the release number by combining the method mentioned here to get the current template list and use AppID to find the most recent version number and then calculate and add it automatically.

Build Mini Program

To build Mini Program, we will directly follow the ability of uni-app to build. Encapsulate the following methods to build Mini Program

/ / miniProgramService.ts partial code public async buildMPForLocal (env: string): Promise {let buildEnv; switch (env.toUpperCase ()) {case "PROD": buildEnv = EnvEnum.prod; break; case "STAGING": buildEnv = EnvEnum.staging; break; case "TEST": buildEnv = EnvEnum.test; break; default: buildEnv = EnvEnum.dev; break } const args = `. / node_modules/.bin/cross-env NODE_ENV=production DEPLOY_ENV=$ {buildEnv} UNI_PLATFORM=mp-weixin. / node_modules/.bin/vue-cli-service uni- build`.split ('') / / normally, you need to pass the shell parameter / / [/ / 'NODE_ENV=production', / /' DEPLOY_ENV=staging', / / 'UNI_PLATFORM=mp-weixin', / /'. / node_modules/.bin/vue-cli-service', / / 'uni-build' / /] const options: MPExecOptions = {execFileNameOrPath:' node', cwd: getWorkspacePath ()} Return Shell.exec (args, options);}

The remaining features

The remaining files are read and modified normally by using the readFileSync method of the fs library.

Undo the modification file through the ability to call Git's checkout command, which is also called using the basic capabilities of Git in the previous chapter

Deploy Mini Program

We have finished build, how to upload it? WeChat Mini Programs still needs to upload this piece with the help of Wechat development tools.

Upload Wechat development tools

First of all, we need to check the developer tool settings: you need to open the service port in the developer tool settings-> security settings. So that we can directly evoke developers and do what we have to do.

In addition, we need to know the address of the execution file of the Wechat developer tool. Normally, Mac address

/ Applications/wechatwebdevtools.app/Contents/MacOS/cli

Finally, it is done through the ability to execute Shell commands provided by us before. Isn't it easy. We also encapsulated miniProgram.ts to do this.

/ / miniProgram.ts core code export namespace Cmd {export function uploadMP (options: MiniProgramExecOptions) {const args = ['upload','-- project', options.projectPath,'- vault, options.userVersion,'- upload', options.userDesc,]; return Core.exec (args, options);}

The remaining features

You can directly call the Wechat open platform api by moving to the template library and deploying the preview version.

Preview of the effect:

The end.

So far, several key technical points implemented in the Vscode plug-in for the entire Mini Program deployment have been briefly explained one by one. Will you think that it is actually not difficult, that is, it involves more things. In fact, there are other things that are not mentioned in detail in this article, such as how to visualize the entire build process steps, some basic capabilities in the Vscode plug-in, and so on.

In fact, the Vscode plug-in is only one link in the whole development efficiency scenario. We will use Dunhuang workbench as the core base with Chrome plug-in, Vscode plug-in and zoo-cli to form a treasure chest of development efficiency. The Vscode plug-in is more about giving developers an immersive development experience.

On how to release WeChat Mini Programs in vscode to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 300

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report