How to publish WeChat applet in vscode (detailed steps)
How to publish WeChat applet in vscode? The following article will share with you the method, I hope it will be helpful to you!
#We often encounter a lot of troublesome things during development. Some processes are smelly and long, like the steps of an old lady's feet. For example, our dear little program, the process and steps make my Mac 13-inch Beggar's Edition very painful. You have to open N many things every time before you can publish to preview. Lan Shou is such a annoying little goblin.
Analysis and dismantling
About Vscode plug-in development basic tutorialPlease move to the official documentation, I won’t go into details here. Here we only focus on realizing the key points of automatic construction and release of small programs.
Since we use uni-app as a unified direction for multiple terminals, we need to go through the following steps every time we develop or test a small program that needs to be sent to the preview version:
Okay, now that the process has been roughly clarified, let us, who have the rigorous attitude of programmers, analyze what abilities are needed in the whole process? Next, we will only do some analysis and dismantling of the key parts of each link, and will not do a complete structure and code analysis of the Vscode plug-in code.
- Pre-work
- Select the build branch, version and fill in the description
- Vscode plug-in window capability-enter the description and select the drop-down box
- Git Ability - Pull branch
- Temporarily save the current branch modification
- Git ability-Save the current branch
- Switch to the target branch
- Git ability - switch branch
- Select the build branch, version and fill in the description
- Local build
- Automatically generate version number
- WeChat development platform api ability - get the current AppID recent template list
- Inject the target applet AppID
- Shell calling ability-modify the file content and inject the AppID
- Run uni-app build command
- Shell calling ability-execute build command
- Undo publishing temporary modified file
- Git calling ability-use Git to undo modified files
##Deploy applet - Automatically generate version number
- Upload cloud draft box
- WeChat development tool calling ability
Move to template library- WeChat development platform api capability
Deploy preview version- Dubbo capability-due to the post The accessToken capability of the WeChat development platform already exists on the client. You can directly call it to obtain the
Shell invocation
When you hear Shell, your anus tightens. People who are not familiar with it think it is very complicated. In fact, it is just usingchild_process Go and start a child process, and then you can have fun. So we encapsulated a shell.ts in the project to perform all Shell script execution actions.
If you are not familiar with child_process, please go here
// shell.ts 部分核心代码 import { execFile, ExecFileOptions } from "child_process"; export namespace Shell { // 在 shell 中直接调用 git 的执行文件执行原始命令 export async function exec<TOut extends string | Buffer>( args: any[], options: ExecFileOptions = {} ): Promise<TOut> { const { stdin, stdinEncoding, execFileNameOrPath, ...opts }: any = { maxBuffer: 100 * 1024 * 1024, ...options, }; return new Promise<TOut>((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 } }); } }
Git call
With the previous Shell as the basis, we can start calling Git. The first parameter in the Shell is the execution file of the command, so we need to get the current The address of the Git execution file is used as the first parameter, and the following is actually the splicing of normal Git commands. So how do you know the current Git execution file path? Getextensions.getExtension("vscode.git") through the Git capability integrated in the Vscode plug-in, as follows
// 获取 Vscode 内置的 Git Api static async getBuiltInGitApi(): Promise<BuiltInGitApi | undefined> { 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; }
gitApi.git.path is the path to the execution file of Git. For more convenient calling, we have also encapsulated a git.ts as the core and most basic call of Git
//git.ts 的部分核心代码 export namespace Git { export namespace Core { // 在 shell 中直接调用 git 的执行文件执行原始命令 export async function exec<TOut extends string | Buffer>( args: any[], options: GitExecOptions = {} ): Promise<TOut> { 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); } }
WeChat development tool call
First choice is tocheck the developer tool settings: You need to open the service port in the developer tool settings-> security settings. In this way we can directly call the developer and do what we want to do.
再者我们需要知道微信开发者工具的执行文件地址。 详细请移步文档
macOS: <安装路径>/Contents/MacOS/cli
windows: <安装路径>/cli.bat
正常来说 Mac 地址 /Applications/wechatwebdevtools.app/Contents/MacOS/cli
最后通过我们以前提供的 Shell 命令能力去执行就搞定了。是不是很简单。我们也封装了miniProgram.ts 来做这个事情
//miniProgram.ts 核心代码 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 { // 在 shell 中直接调用 git 的执行文件执行原始命令 export async function exec<TOut extends string | Buffer>( args: any[], options: MiniProgramExecOptions ): Promise<TOut> { vscode; options.execFileNameOrPath = "/Applications/wechatwebdevtools.app/Contents/MacOS/cli"; return Shell.exec(args, options); } } }
Duddo 的调用
不明觉厉,都直接调 Dubbo 了吊的不行,其实很简单,有一个 nodeJs 的库 node-zookeeper-dubbo
再配合 js-to-java
这两个库就能搞定,只不过一些配置比较麻烦,我就把代码大致的贴出来
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: "你的项目名称", //项目名称 register: "你的服务器地址", // zookeeper 服务器地址,多个服务器之间使用逗号分割 dubboVer: "你的版本", //dubbo 的版本,询问后端得知是2.3.5 root: '你的根节点', //注册到 zookeeper 上的根节点名称 dependencies: { //依赖的 dubbo 服务集,也就是你要调用的服务的配置集合 mp: { //服务的标识,自定义的,按自己喜好 interface: "你的后端 dubbo 服务地址", //后端 dubbo 服务地址 version: "你的服务版本号", //服务版本号 timeout: "30000", //超时时间 group: '你的分组', //分组的功能也没有使用 methodSignature: { //服务里暴露的方法的签名,可以省略 getComponentToken: () => () => [], }, }, }, java: j2j, //使用 js-to-java 库来简化传递给 java 后端的值的写法 }; this._dubbo = new nzd(options); } }
至此一些基本能力已经封装的差不多了
Shell:Shell.exec 方法
Git:Git.Core.exec 方法
微信开发工具: MiniProgram.Core.exec 方法
Dubbo: DobboService.dubbo.mp 方法
搞起
前置工作
因为我们要构建一个预发版,所以很有可能我们需要构建的分支不是我们当前工作的分支,所以这步骤的话更多的是要做好一些构建前的一些准备工作,总不能因为人家测试要一个预览测试版然后一不小心把我们自己本地的辛辛苦苦开发的东西弄没了吧,那真的是 f**k 了。
根据流程我们先来分解下大致的技术动作
- 临时保存当前分支修改
- 获取当前分支。
- 如果是在当前分支啥都不管,否则 stash 下
- 切换到需要发布分支
- 切换下分支
再精简下: 获取当前分支 ---> 保存修改 --> 切换分支。 都是 Git 的一些动作。那么在 nodeJs 中怎么开始自己的 Git 表演呢?一个关键点:Shell 脚本和命令的调用,所以这里的本质是调用 Shell。我们在上个章节中已经实现的 Shell 和 Git 的基本能力了,我们直接调用就行了。
使用 symbolic-ref 获取当前分支
其实 Git 的命令分为两种
- 高层命令(porcelain commands)
- 底层命令(plumbing commands)
常用的命令大家都很熟悉了,什么 branch 啊, init 啊,add 啊,commit 啊等等。底层命令又是什么鬼,其实所有的高层命令的本质都是会调用底层命令,可以类比为语言层面 Java,C#,Js 这些高级语言他的底层是使用 C 或者 C++ 是一个概念。 有兴趣请移步
symbolic-ref 命令能干嘛呢?
给定一个参数,读取哪个分支头部给定的符号 ref 引用并输出其相对于 .git/
目录的路径。通常,HEAD
以 参数的形式提供您的工作树所在的分支。
有了上面 git.ts 支持基本能力那么现在我们就很简单多了,Git.Core.exec<string>(["symbolic-ref", "--short", "HEAD"], options);
在 git.ts 中增加基本命令方法
// git.ts 部分代码 export function symbolicRef(options: GitExecOptions = {}) { return Core.exec<string>(["symbolic-ref", "--short", "HEAD"], options); }
在 gitService 中实现 getCurrentBranch 方法
// gitService.ts 部分代码 public async getCurrentBranch(filePath: string): Promise<string> { const branchName = await Git.Cmd.symbolicRef({ cwd: filePath }); return branchName.replace(/\n/g, ""); }
保存修改和切换分支
当我们获取到当前分支之后,和我们目标分支进行比对如果一致的话直接跳过该步骤,否则就需要对当前分支保存并且切换了。
为了方便对于保存和切换我们直接用了Git 的 stash 和 checkout 命令,并且封装了两个方法。
// git.ts 部分代码 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<string>(params, options); } export function stash(options: GitExecOptions = {}) { const params = [ "stash" ]; if (options.stashPop) { params.push('pop'); } return Core.exec<string>(params, options); }
本地构建
继续分析下本地构建的基本流程
大致分以下几步
- 自动生成版本号
- 得到当前 AppID 在微信模板库中版本号情况
- 注入需要发布的小程序 AppID
- 需要修改 src/manifest.json 文件中 AppID,方便开发工具上传使用
- 运行 uni-app 构建命令
- run uniapp 命令
- 撤销发布时候的临时文件修改
- 撤销文件修改
能力上来说有那么几个
微信 api 调用
文件读取和修改能力
Shell 命令执行能力
撤销文件修改能力
首先怎么调用微信的 api,由于那时候我们亲爱的后端同学啃次啃次的已经吧微信 token 鉴权的能力已经做掉了,所以我们直接接后端的微信鉴权能力就可以了。但是怎么接又是个问题,虽然人家已经有个 restful 接口可以用,但是接口都要登录的啊,让人家为了我这个小小的需求弄个匿名的不大现实也不安全,想来想去那就不要用 restful 了,直接调他后面提供的 Dobbo 服务好了,完美。
获取微信 accessToken
在获取微信 api 调用前我们需要先得到 accessToken。
所以我们会先用一个公共方法先去获取当前 accessToken, 然后在去请求微信开发平台 api。
// miniProgramService.ts 部分代码 public async retrieveWxToken(): Promise<string> { if (!Launcher.dobboService.dubbo.mp) { throw new Error("dubbo初始化错误"); } const { success: dobboSuccess, error, result: wxToken, } = await Launcher.dobboService.dubbo.mp.getComponentToken(); if (!dobboSuccess) { throw new Error(`dubbo调用失败:${error}`); } console.log("wxToken:", wxToken); return wxToken; }
如果你们的后端没有支持微信开发平台的鉴权能力的话就需要自己用 nodejs 方式去实现了,具体的微信开放平台文案请移步
微信开放平台 api 调用
其实微信开放平台 api 调用就是正常的 http 调用即可。
微信提供了一系列方法,对于我们这次的场景来说有如下接口
getTemplateList 获取模板列表
POST https://api.weixin.qq.com/wxa/gettemplatelist?access_token==ACCESS_TOKEN
Copy after login
addtotemplate 移动草稿到模板库
POST https://api.weixin.qq.com/wxa/gettemplatelist?access_token=ACCESS_TOKEN
Copy after login
deleteTemplate 删除指定模板
POST https://api.weixin.qq.com/wxa/deletetemplate?access_token=ACCESS_TOKEN
Copy after login
getTemplateDraftList 获取草稿箱列表
https://api.weixin.qq.com/wxa/gettemplatedraftlist?access_token=ACCESS_TOKEN
Copy after login
版本号的自动生成主要是通过在你点击发布时候通过让用户选择发布的版本为“大版本”,“功能迭代”还是“补丁修复”,在结合这里提到的获取当前模板列表并用 AppID 找到当前最近的版本号再做自动计算累加的方式得到这次发布的版本号。
构建小程序
构建小程序这边就直接沿用 uni-app 的能力直接做构建。封装了如下方法去构建小程序
//miniProgramService.ts 部分代码 public async buildMPForLocal(env: string): Promise<string> { 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(' '); //正常需要这样传入 shell 参数才行 //[ // '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); }
其余的功能
- 剩余文件读取就正常使用 fs 库的 readFileSync 方法去读取和修改
- 撤销修改文件则是通过调用 Git 的 checkout 命令的能力去做,也是要使用上一章节的 Git 的基本能力调用
部署小程序
我们 build 完成了,怎么上传呢?微信小程序这块还是需要借助微信开发工具的能力来上传
微信开发工具上传
首选我们要先检查开发者工具设置:需要在开发者工具的设置 -> 安全设置中开启服务端口。这样我们才能直接唤起开发者然后做些我们要做的事情。
再者我们需要知道微信开发者工具的执行文件地址。正常来说 Mac 地址
/Applications/wechatwebdevtools.app/Contents/MacOS/cli
最后通过我们以前提供的 Shell 命令能力去执行就搞定了。是不是很简单。我们也封装了miniProgram.ts 来做这个事情
// miniProgram.ts 核心代码 export namespace Cmd { export function uploadMP(options: MiniProgramExecOptions) { const args = [ 'upload', '--project', options.projectPath, '-v', options.userVersion, '-d', options.userDesc, ]; return Core.exec<string>(args, options); } } }
其余的功能
- 移动到模板库和部署预览版直接调用微信开放平台 api 即可
效果预览图:
尾声
至此整个小程序部署的在 Vscode 插件中实现的几个关键的技术点已经逐一做了简要的说明,大家会不会觉得其实看下来不难,就是涉及的东西会比较多。其实还有其他的诸如整个构建流程步骤如何可视化,Vscode 插件里面的一些基础的能力等等在本文都没有详细提及。欢迎大家留言或者提问把自己想要知道的问题反馈给我们,也方便我们可以针对大家的问题再去做一篇更棒的关于 Vscode 插件开发的文章。
其实 Vscode 插件在整个开发提效场景中只是当中的一个环节,我们会以敦煌工作台为核心底座搭配 Chrome 插件,Vscode 插件,zoo-cli 形成一个开发提效的百宝箱。Vscode 插件更多的是想给开发者们带来沉浸式开发的体验。
原文地址:https://juejin.cn/post/7000138685274390542#heading-6
For more programming related knowledge, please visit: Programming Video! !
The above is the detailed content of How to publish WeChat applet in vscode (detailed steps). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to define header files using Visual Studio Code? Create a header file and declare symbols in the header file using the .h or .hpp suffix name (such as classes, functions, variables) Compile the program using the #include directive to include the header file in the source file. The header file will be included and the declared symbols are available.

VS Code system requirements: Operating system: Windows 10 and above, macOS 10.12 and above, Linux distribution processor: minimum 1.6 GHz, recommended 2.0 GHz and above memory: minimum 512 MB, recommended 4 GB and above storage space: minimum 250 MB, recommended 1 GB and above other requirements: stable network connection, Xorg/Wayland (Linux)

How to solve the problem that Chinese comments in Visual Studio Code become question marks: Check the file encoding and make sure it is "UTF-8 without BOM". Change the font to a font that supports Chinese characters, such as "Song Style" or "Microsoft Yahei". Reinstall the font. Enable Unicode support. Upgrade VSCode, restart the computer, and recreate the source file.

Common commands for VS Code terminals include: Clear the terminal screen (clear), list the current directory file (ls), change the current working directory (cd), print the current working directory path (pwd), create a new directory (mkdir), delete empty directory (rmdir), create a new file (touch) delete a file or directory (rm), copy a file or directory (cp), move or rename a file or directory (mv) display file content (cat) view file content and scroll (less) view file content only scroll down (more) display the first few lines of the file (head)

vscode built-in terminal is a development tool that allows running commands and scripts within the editor to simplify the development process. How to use vscode terminal: Open the terminal with the shortcut key (Ctrl/Cmd). Enter a command or run the script. Use hotkeys (such as Ctrl L to clear the terminal). Change the working directory (such as the cd command). Advanced features include debug mode, automatic code snippet completion, and interactive command history.

Visual Studio Code (VSCode) is a cross-platform, open source and free code editor developed by Microsoft. It is known for its lightweight, scalability and support for a wide range of programming languages. To install VSCode, please visit the official website to download and run the installer. When using VSCode, you can create new projects, edit code, debug code, navigate projects, expand VSCode, and manage settings. VSCode is available for Windows, macOS, and Linux, supports multiple programming languages and provides various extensions through Marketplace. Its advantages include lightweight, scalability, extensive language support, rich features and version

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Causes and solutions for the VS Code terminal commands not available: The necessary tools are not installed (Windows: WSL; macOS: Xcode command line tools) Path configuration is wrong (add executable files to PATH environment variables) Permission issues (run VS Code as administrator) Firewall or proxy restrictions (check settings, unrestrictions) Terminal settings are incorrect (enable use of external terminals) VS Code installation is corrupt (reinstall or update) Terminal configuration is incompatible (try different terminal types or commands) Specific environment variables are missing (set necessary environment variables)
