NavigateTo ({url:” XXX “}); navigateTo({url:” XXX “}); navigateTo({url:” XXX “}) Is there a way to generate all the routing functions at once? And you don’t need concatenation parameters? The answer is Taro’s plugins.

First, write a local plug-in

1, create,

Visit the Taro official documentation for an advanced guide -> Plug-in features, which explains how to use plug-ins. Since we didn’t need to distribute the NPM package, we used the local plug-in.

const config = {
  plugins: [
    // Import NPM installed plug-ins
    '@tarojs/plugin-mock'.// Import the plugin installed by NPM and pass in the plugin parameters
    ['@tarojs/plugin-mock', {
      mocks: {
        '/api/user/1': {
          name: 'judy'.desc: 'Mental guy'}}}].// Import the plug-in from the local absolute path, as well as passing in parameters if needed
    '/absulute/path/plugin/filename']},Copy the code

Create plugin -> xxx.js in the project root directory and import it in config->index.js

2, write,

I don’t know whether I opened the project in the wrong way or some other reason, the example in the official document reported an error at the start of the project. Later, we modified the export module mode to solve the problem.

2.1 the main body

export default (ctx, options) => {
  / / the plugin
  ctx.onBuildStart(() = > {
    console.log('Compilation begins! ')
  })
  ctx.onBuildFinish(() = > {
    console.log('Compile complete! ')})}Copy the code

Instead of

module.exports = (ctx, options) = > {
  / / the plugin
  ctx.onBuildStart(() = > {
    console.log('Compilation begins! ')
  })
  ctx.onBuildFinish(() = > {
    console.log('Compile complete! ')})}Copy the code

2.2 Generating a Template

Figure out the routing function template you want to generate. Since the project uses TS, my template is as follows

import Taro, { EventChannel, General } from "@tarojs/taro";

export enum NavigateType {
  /** Keep the current page and jump to a page in the application. But you cannot jump to the Tabbar page. Use router. back to return to the original page. The page stack in the applets is up to ten layers. * /
  navigateTo = "navigateTo"./** Close the current page to jump to a page in the application. However, jumping to the Tabbar page is not allowed. * /
  redirectTo = "redirectTo"./** Close all pages to open a page within the app */
  reLaunch = "reLaunch"./** Jump to the tabBar page and close all other non-tabbar pages */
  switchTab = "switchTab", } interface ToRouterType<P> { params? : P; type? : NavigateType/** The interface calls the end of the callback function (call on success or failure) */; complete? :(res: General.CallbackResult) = > void;
  /** Interpage communication interface, used to listen to the data sent from the opened page to the current page. * /events? : General.IAnyObject;/** interface calls failed callback function */fail? :(res: General.CallbackResult) = > void;
  /** The interface successfully called the callback function */success? :(
    res: General.CallbackResult & { eventChannel: EventChannel }
  ) = > void;
}

const navigateType = <P>(url: string, option? : ToRouterType

) = >
{ const { type, params, success, fail, complete, events } = option ?? { type: NavigateType.navigateTo, params: {}, success: () = > {}, fail: () = > {}, complete: () = > {}, events: undefined}; url = url + ganerateParams(params ?? {});switch (type) { case NavigateType.navigateTo: Taro.navigateTo({ url, success, fail, complete, events }); break; case NavigateType.redirectTo: Taro.redirectTo({ url, success, fail, complete }); break; case NavigateType.reLaunch: Taro.reLaunch({ url, success, fail, complete }); break; case NavigateType.switchTab: Taro.switchTab({ url, success, fail, complete }); break; default: Taro.navigateTo({ url, success, fail, complete, events }); }};const ganerateParams = (params: { [key: string]: any }) = > { return ( "?" + Object.entries(params).reduce((total, cur, idx) = > { const val = cur[0] + "=" + cur[1]; if (idx === Object.entries(params).length - 1) { return total + val; } else { return total + val + "&"; }},"")); };Copy the code

2.3 Generating Logic

The next step is to write the build logic

const path = require("path");

module.exports = (ctx, options) = > {
 ctx.registerCommand({
    / / the command name
    name: "generate-router-methods".async fn() {
      console.log("Start generating");
      const appConfigPath = ctx.helper.resolveMainFilePath(
        path.resolve(ctx.paths.sourcePath, "./app.config"));const appConfig = ctx.helper.readConfig(appConfigPath);
      let pagePath = [...appConfig.pages.map((page) = > ` /${page}`)];
      // The following logic is based on the subcontracting strategy of the official website. You can also write different logic according to your own subcontracting method
      if (appConfig.subPackages) {
        appConfig.subPackages.forEach((package) = > {
          package.pages.forEach((packagePage) = > {
            pagePath.push(` /${package.root}/${packagePage}`);
          });
        });
      }
      // console.log(appConfig);
      console.log(pagePath);
      ctx.helper.fs.writeFile(
        ctx.paths.sourcePath + "/utils/toRouterPage.ts",
        generateToRouterMethods(pagePath),
        function (err) {
          console.log(Generate -- routing function (${pagePath.length}A) `);
          if (err) {
            throwerr; }}); }}); };function generateToRouterMethods(pagePath) {
  const staticStr = 'Template content';
   // Generate routing methods based on your own template. You can customize method names.
  const toRouterMethodsStr = pagePath
    .map((item) = > {
      const routerSplit = item
        .split("/")
        .map(
          (routerSplitItem) = >
            routerSplitItem.charAt(0).toUpperCase() + routerSplitItem.slice(1));let methodName = "";
      if (routerSplit.length > 4) {
        methodName = routerSplit[1] + routerSplit[3];
      } else {
        methodName = routerSplit[2];
      }
      return `
export const to${
        methodName.charAt(0).toUpperCase() + methodName.slice(1)}Page = <P>(option? : ToRouterType<P>) => { navigateType("${item}", option);
};
`;
    })
    .join("\n");

  return staticStr + toRouterMethodsStr;
}
Copy the code

Then execute taro generate-Router-methods on the console to generate the function