Home > Development Tools > VSCode > How to publish WeChat applet in vscode (detailed steps)

How to publish WeChat applet in vscode (detailed steps)

青灯夜游
Release: 2021-09-26 19:56:11
forward
5840 people have browsed it

How to publish WeChat applet in vscode? The following article will share with you the method, I hope it will be helpful to you!

How to publish WeChat applet in vscode (detailed steps)

#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:

How to publish WeChat applet in vscode (detailed steps)

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.

  1. 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
  2. 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
  3. ##Deploy applet
    • 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
. The window capability of the Vscode plug-in is provided by default and does not need to be implemented, so Shell Calls, Git calls, Dubbo calls, WeChat development platform API calls, and WeChat development tool calls need to be implemented.

Reclassification, in fact, Git calls and WeChat development tool calls are command line calls, that is, Shell calls. WeChat development platform api calls are actually http requests, but the most important accessKey is Directly call the Zhengcai Cloud backend Dubbo interface to obtain it, so Dubbo is needed. Let’s take a look at how to do it?

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 using

child_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(&#39;error&#39;); }
      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
      }
    });
  }
}
Copy after login

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

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?

Get

extensions.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;
  }
Copy after login

In the returned object

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);
    }
}
Copy after login

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

WeChat development tool call

First choice is to

check 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 &#39;../shell&#39;;

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);
    }
  }
}
Copy after login

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: &#39;你的根节点&#39;, //注册到 zookeeper 上的根节点名称
      dependencies: {
        //依赖的 dubbo 服务集,也就是你要调用的服务的配置集合
        mp: {
          //服务的标识,自定义的,按自己喜好
          interface: "你的后端 dubbo 服务地址", //后端 dubbo 服务地址
          version: "你的服务版本号", //服务版本号
          timeout: "30000", //超时时间
          group: &#39;你的分组&#39;, //分组的功能也没有使用
          methodSignature: {
            //服务里暴露的方法的签名,可以省略
            getComponentToken: () => () => [],
          },
        },
      },
      java: j2j, //使用 js-to-java 库来简化传递给 java  后端的值的写法
    };
    this._dubbo = new nzd(options);
  }
}
Copy after login

至此一些基本能力已经封装的差不多了

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);
}
Copy after login

在 gitService 中实现 getCurrentBranch 方法

// gitService.ts 部分代码
public async getCurrentBranch(filePath: string): Promise<string> {
    const branchName = await Git.Cmd.symbolicRef({ cwd: filePath });
    return branchName.replace(/\n/g, "");
}
Copy after login

保存修改和切换分支

当我们获取到当前分支之后,和我们目标分支进行比对如果一致的话直接跳过该步骤,否则就需要对当前分支保存并且切换了。

为了方便对于保存和切换我们直接用了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(&#39;--&#39;,options.fileName);
      }
      return Core.exec<string>(params, options);
    }
    
    export function stash(options: GitExecOptions = {}) {
      const params = [
        "stash"
      ];
      if (options.stashPop) {
        params.push(&#39;pop&#39;);
      }
      return Core.exec<string>(params, options);
    }
Copy after login

本地构建

继续分析下本地构建的基本流程

大致分以下几步

  • 自动生成版本号
    • 得到当前 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;
  }
Copy after login

如果你们的后端没有支持微信开发平台的鉴权能力的话就需要自己用 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(&#39; &#39;);
    //正常需要这样传入 shell 参数才行
    //[
    // &#39;NODE_ENV=production&#39;,
    // &#39;DEPLOY_ENV=staging&#39;,
    // &#39;UNI_PLATFORM=mp-weixin&#39;,
    // &#39;./node_modules/.bin/vue-cli-service&#39;,
    // &#39;uni-build&#39;
    //]

    const options: MPExecOptions = {
      execFileNameOrPath: &#39;node&#39;,
      cwd: getWorkspacePath()
    };

    return Shell.exec(args, options);
  }
Copy after login

其余的功能

  • 剩余文件读取就正常使用 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 = [
        &#39;upload&#39;,
        &#39;--project&#39;,
        options.projectPath,
        &#39;-v&#39;,
        options.userVersion,
        &#39;-d&#39;,
        options.userDesc,
      ];
      return Core.exec<string>(args, options);
    }
  }
}
Copy after login

其余的功能

  • 移动到模板库和部署预览版直接调用微信开放平台 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!

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template