SoFunction
Updated on 2025-04-07

Detailed explanation of how the WeChat applet version mechanism and storage are smoothly compatible

Problem background

A mini program will have a defaultThree versions(development, experience, production), andSame unitOpen your phoneThe same appletWill only correspondA local storage(storage), which will cause us to record certain information in the local storage because we have usedDifferent versionsmini program,Local storageThere will be mismatch or overwritten situations. To solve this problem, we will design a feasible solution.

Mini Program Version

Click here for the official documentation

  • Development Editiondevelop: Local preview, local real machine debugging The corresponding mini program version is only used on the current developer's equipment. Generally, the debugging function in the development stage is generated and used at one time.
  • Experience versiontrial: After local development is completed, the current version will generally be uploaded to the mini program background. The mini program background will have corresponding version records. You can set the uploaded version to the trial version forExperience versionUsed by project personnel.
  • Production versionrelease: That is, the online version after release, which can be used by everyone.

Local storage of applets

Click here for the official documentation

If you are familiar with the web, it should be easy to understand. The local storage of mini programs is the same as the local storage of web, and there will be local storage.storage, you can directly read the official document using the specific API, and the storage format is onekeyCorresponding to onevalue. As mentioned in the background above, because there are multiple versions of the applet, but only one applet will be stored locally.storage, so use api to read and writestorageWhen it comes to this, it is impossible to distinguish between the mini program version, especially when project personnel with experience copyrights, when using the production version for the first time, the experience effect of opening the official version for the first time will be affected by the local storage of the experience version. Let’s list feasible solutions below.

Solution 1: Read and write plus flags

becausestorageThe data format isKey-value pairsone key one value, then we can read and writestorageAdd it wheneverVersionDistinguish, so that the keys and values ​​will naturally be separated.

I'll write down the rough pseudo-code

// Local storage key name mapconst STORAGE_KEY_MAP = {
  /** api environment */
 API_HOST: '__api_host__'
};

// Settings Development Version Fields(STORAGE_KEY_MAP.API_HOST + '@develop', 'dev1');

// Settings Experience Version Fields(STORAGE_KEY_MAP.API_HOST  + '@trial', 'dev1');

// Set the production version field (without the version suffix)(STORAGE_KEY_MAP.API_HOST , 'dev1');

// Read(STORAGE_KEY_MAP.API_HOST + '@develop');
(STORAGE_KEY_MAP.API_HOST  + '@trial');
(STORAGE_KEY_MAP.API_HOST)

Read and write by adding the version flag to the key namestorageNone will be affected by the version anymore. This is the most basic and direct way, because the size of local storage is 10M. We use 👆🏻 This method is equivalent to storing three versions of local storage data at the same time. It will feel a bit redundant when using this method alone. In order to use local storage more elegantly, I recommend using the second solution provided below.

Solution 2: Read and write plus flag + Monitor production version updates

This solution will not affect the production version, and there will only be one copy of data locally after it is launched. In combination with Solution 1, we have improved the process by monitoring the production version update and clearing itstorage

Explain what it means, because it is mainlyExperience versionandProduction versionBetweenstorageIt will have an impact. Before a mini program goes online, there will be a group of people with experience permissions to try out the version that will be launched this time. When the same group of people open the applet after release, readstorageIt will be the data stored locally in the last time using the trial version. To make these two versions ofstorageIsolation, we need to use Solution 1, first let’s try the versionstorageAfter the production version is released, when the production version is opened, the storage previously marked as the trial version is cleared, so that only one version of storage will exist for each version (why? Because the next experience version must be based on the previous production version. When the previous production version is used, we have already made the previous non-production version storage clear, so when using the new trial version, we actually return to an initialized state).

Using this solution is relatively reasonable in the positive process of "Development->Test->Publish", that is, after each release, the non-production version of the applet starts to record local storage again.

There are three things to pay attention to here.

  • The update mechanism of mini program: when cold starts, the mini program is opened for the first time, or the mini program is automatically destroyed after more than 30 minutes, and the default update will be updated toLatest versionmini program (user has no sense). When the applet is still hot-start (it is in use for the time being, and the foreground has not been hidden), it isWon'tYou should immediately download the new version. If you want to update the mini program during the hot start period, you must manually obtain the latest version of the mini program by "Delete the mini program and re-enter the mini program".
  • The monitoring version management API provided by the applet allows us to sense whether there is a latest version released in the background when using the local old version. Notice:Non-production versionThis applet has no concept of version number, and cannot use version update monitoring. You can change the compilation mode setting to simulate updates.
  • Because we need to clear the non-production versionstorage, so we set it up in the early stagestorageWhen you have tokey Unified maintenance, so that we can directly know that we will set upstorageKey Map for batch deletion.

Let's write about the relevant implementations below

Version definition

// Versionconst APP_ENV_MAP = {
  /** Development Edition */
  develop: "develop",
  /** Experience version */
  trial: "trial",
  /** Production version */
  release: "release",
};

Get the current applet version

Using apigetAccountInfoSyncThe mini program version information will be returned

// Get the current applet versionfunction getEnvByAccountInfo() {
  try {
    const accountInfo = ();
    return ; // Version  } catch (error) {
    return null;
  }
}

// Is it currently a production versionconst IS_RELEASE = getEnvByAccountInfo() === APP_ENV_MAP.release;

Production new version monitoring

Using apigetUpdateManagerManage applet updates

STORAGE_KEY_MAPIt is a well-maintained storage key map collection.IS_RELEASEIt is to determine whether the current version is a production version applet

// 
onLaunch: function () {
    // Get applet update management    const updateManager = ();

    // Listen to whether there is a new version    (function (res) {
      // All trial version keys      const allTrialKeys = (STORAGE_KEY_MAP).map((key) =>
        getEnvStorageKey(key, APP_ENV_MAP.trial)
      );

      // All development keys      const allDevKeys = (STORAGE_KEY_MAP).map((key) =>
        getEnvStorageKey(key, APP_ENV_MAP.develop)
      );

      // Currently it is a production version and there is a new production version      if (IS_RELEASE && ) {
        // There is no batch deleted API, so I can only delete it like this        [...allTrialKeys, ...allDevKeys].forEach((key) => {
          (key);
        });
      }
    });
  },

This is probably what the whole process is

Summarize

This is the article about how smoothly compatible WeChat applet version mechanism and storage are introduced here. For more related applet version mechanism and storage, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!