Small program unpacking

The subcontract

In some cases, the developer needs to divide the applets into different subpackages, which are packaged into different subpackages at build time and loaded by users as needed.

When building a applets subcontract project, the build outputs one or more subcontracts. Each subcontracting applet must contain a main package. The main package, which places the default startup page /TabBar page, and some common resource /JS scripts for all the subpackages; Subcontracting is divided according to the developer’s configuration.

When the small program starts, the main package will be downloaded and the page in the main package will be started by default. When the user enters a page in the subpackage, the client will download the corresponding subpackage and display it after downloading.

Currently, the subcontracting size of small program has the following limitations:

  • The whole small program all subcontracting size is not more than 20M
  • The size of a single subcontract/main package cannot exceed 2M

Subcontracting the applets optimizes the download time for the first startup of the applets and allows better decoupling and collaboration when multiple teams work together

Packaging principles

  • The statementsubpackagesLater, will besubpackagesConfigure paths for packaging,subpackagesDirectories outside the configuration path will be packaged into the APP (main package)
  • An APP (main package) can also have its own Pages (the outermost Pages field)
  • subpackageThe root directory of “cannot be anothersubpackageSubdirectories in
  • tabBarPages must be in app (main package)

Refer to the principle of

  • packageACan’t the requirepackageBJS file, but can requireapp, JS files in your package; useSubcontracting asynchronizationIs not subject to this restriction
  • packageAUnable to importpackageBTemplate, but can requireappThe template in your own package
  • packageACan’t usepackageBResources, but can be usedapp, resources within your own package

Independent of the subcontract

Independent subcontracting is a special type of subcontracting in small programs that can operate independently of the main package and other subcontracting. There is no need to download the main package when entering the applet from the standalone subcontracting page. The main package is downloaded only when the user enters the normal package or main package page.

Developers can configure certain functional independence pages into independent subcontracting as needed. When the applets start from the normal subcontracting page, the main package needs to be downloaded first; Independent subcontracting can run independently of the main package, which can greatly improve the startup speed of the subcontracting page.

You can have multiple independent subcontractors in a small program

The developer declares the subpackages to be independent subpackages by defining the independent field in the corresponding subpackages configuration item in app.json

limit

Independent subcontracting is a kind of subcontracting. All restrictions on ordinary subcontracting are in effect for independent subcontracting. Plug-ins and custom components in independent subcontracting are treated in the same way as ordinary subcontracting.

In addition, when using independent subcontracting, note:

  • Independent subcontracting cannot rely on the contents of the main package and other subcontracting, including JS files, templates, WXSS, custom components, plug-ins, etc. (Js files, custom components, plug-ins are not restricted by this clause when subcontracting asynchronization is used)
  • The main in the packageapp.wxssNot valid for independent subcontracting and should be avoided in independent subcontracting pagesapp.wxssThe style in;
  • AppCan only be defined in the main package, not in independent subcontractingApp, can cause unexpected behavior;
  • Plugins are not currently supported in standalone subcontracting.

Matters needing attention

(1) AboutgetApp()

Unlike normal subcontracting, when standalone subcontracting runs, App is not necessarily registered, so getApp() does not necessarily get the App object:

  • When the user launches the applet from the standalone package page, the main package does not exist,AppAlso does not exist when calledgetApp()What we get is thetaundefined. The main package is only downloaded when the user enters the normal subpackage or main package page,AppTo be registered.
  • When the user jumps to the independent subcontracting page from the normal subcontracting page or the page in the main package, the main package already existsgetApp()You can get the realApp.

Because of this limitation, developers cannot implement independent subcontracting and global variable sharing from other parts of the applet through App objects.

To meet this requirement in standalone subcontracting, the base library version 2.2.4 starts with getApp supporting the [allowDefault] parameter, returning a default implementation if App is not defined. When the main package is loaded and the App is registered, the properties defined in the default implementation are overridden and merged into the real App.

Sample code:

  • Independent subcontracting
const app = getApp({allowDefault: true}) // {}
app.data = 456
app.global = {}
Copy the code
  • App. Js
App({
  data: 123,
  other: 'hello'
})

console.log(getApp()) // {global: {}, data: 456, other: 'hello'}
Copy the code

(2) AboutAppThe life cycle

The onLaunch and first onShow of the App in the main package are called when the main package or other normal package pages are first entered from the independent package page when the applet is launched from the independent package page.

Since App cannot be defined in independent subcontracting, monitoring of the applet life cycle can be done using wx.onAppShow, wx.onAppHide. Other events on the App can be listened for using wx.onError, wx.onPageNotFound.

Subcontract predownload

Base library 2.3.0 starts to support, earlier versions need to be compatible processing. Please use version 1.02.1808300 or later for developer tools, download here.

Developers can configure the framework to automatically download subcontracts that may be needed when entering a certain page of the small program, so as to improve the startup speed when entering subsequent subcontracting pages. For standalone subcontracting, the main package can also be pre-downloaded.

Currently, subcontracting pre-download can only be used in configuration mode, and API invocation is not supported.

The vConsole has log information starting with preloadSubpackages, which can be used to verify pre-downloads.

Configuration method

The preload subcontract behavior is triggered when entering a page and is controlled by adding a preloadRule configuration to app.json.

{
  "pages": ["pages/index"],
  "subpackages": [
    {
      "root": "important",
      "pages": ["index"],
    },
    {
      "root": "sub1",
      "pages": ["index"],
    },
    {
      "name": "hello",
      "root": "path/to",
      "pages": ["index"]
    },
    {
      "root": "sub3",
      "pages": ["index"]
    },
    {
      "root": "indep",
      "pages": ["index"],
      "independent": true
    }
  ],
  "preloadRule": {
    "pages/index": {
      "network": "all",
      "packages": ["important"]
    },
    "sub1/index": {
      "packages": ["hello", "sub3"]
    },
    "sub3/index": {
      "packages": ["path/to"]
    },
    "indep/index": {
      "packages": ["__APP__"]
    }
  }
}
Copy the code

In preloadRule, key is the path to the page, and value is the pre-downloaded configuration to enter the page. Each configuration has the following items:

field type mandatory The default value instructions
packages StringArray is There is no Enter the page after the pre-download subcontractedroot 或 name.__APP__Represents the primary package.
network String no wifi Pre-download on a specified network. The possible values are:all: Unlimited networkwifi: Pre-download only over wifi

limit

Pages in the same subcontract have a common pre-download size limit of 2M, which is verified when packaged in the tool.

For example, both page A and page B are in the same subcontract. Subcontract with A total size of 0.5m can be pre-downloaded in A, and subcontract with A total size of 1.5m can be pre-downloaded in B at most.

Small program live plug-in use

1. How to introduce [Live broadcast component]

Version restriction: wechat client version 7.0.7 and above (base library version 2.9.x and above support the same layer rendering) can watch live broadcast and use the functions of the live broadcast room. In the earlier version, users will be prompted to upgrade the wechat client version when entering the live broadcast room (the earlier version can only watch live broadcast and cannot use the functions of the live broadcast room).

Support to introduce [Live component] live-player-plugin code package in the main package or subpackage (note: Live component is not included in the code package volume), reference app.json in the project root directory, sample code is as follows:

(1) Main package introduction

"Plugins ": {"live-player-plugin": {"version": "1.3.0", // Please fill in the latest version number of the livestreaming component. The latest version number can be obtained during debugging of wechat developer tools (please remove the comment when copying). "provider": "Wx2b03c6e691cd7370" // The appID of the livestream component must be filled in. This example value is the appID of the livestream component (please remove the comment when replicating)}}Copy the code

(2) Introduction of subcontracting

"subpackages": [ { "plugins": { "live-player-plugin": { "version": "1.3.0", // Pay attention to the latest version number of the livestreaming component. The latest version number can be obtained when debugging the wechat developer tool (please remove the comment when copying). "provider": "Wx2b03c6e691cd7370" // Must fill in the appID of the livestream component, which is the example value of the livestream component appID (please remove the comment when replicating)}}}]Copy the code

2. How to use [Live broadcast component]

After introducing the component code package configuration according to the method in Step 1, you can directly jump to the page of the live broadcast component through the link address (namely, the page of the live broadcast room). The link address needs to bring the ID of the live broadcast room. The room ID can be obtained via the get Live Room list API below.

Example code is as follows:

(1) Use navigator component to jump into the live broadcast room

index.js
CustomParams = encodeURIComponent(json.stringify ({path: customParams = encodeURIComponent(json.stringify ({path: 'pages/index/index', pid: 1})) // Developers carry custom parameters (such as PATH and PID parameters in the example) on the path of the webcast page, which can be obtained in the subsequent sharing card link and jump to the business page. For details, see section "Obtaining Custom Parameters" and "Carrying Parameters from webcast to Business page" (maximum 600 characters, This. SetData ({roomId, customParams})Copy the code
index.wxml
<navigator url="plugin-private://wx2b03c6e691cd7370/pages/live-player-plugin? Room_id ={{roomId}}&custom_params={{customParams}}"></navigatorCopy the code

(2) Use navigateTo to jump to the live broadcast room

index.js
CustomParams = encodeURIComponent(json.stringify ({path: customParams = encodeURIComponent(json.stringify ({path: 'pages/index/index', pid: 1})) // Developers carry custom parameters (such as PATH and PID parameters in the example) on the path of the webcast page, which can be obtained in the subsequent sharing card link and jump to the business page. For details, see section "Obtaining Custom Parameters" and "Carrying Parameters from webcast to Business page" (maximum 600 characters, More than part will be truncated) wx. NavigateTo ({url: ` plugin - private: / / wx2b03c6e691cd7370 / pages/live - player - the plugin? Room_id =${roomId}&custom_params=${customParams} '}Copy the code

Through this link, you can jump to the live broadcast component page (currently, only ‘live-player-plugin’ is open at the entrance of the page).

Sample renderings are as follows:

) Live components and interfaces

[Component Interface]

By introducing live streaming components into the main package/subpackage, developers can easily realize functions such as subscription, obtaining live streaming status, obtaining user OpenID, and obtaining link parameters of shared cards.

[Server Interface]

The server interface includes direct broadcast interface and commodity management interface.

  • Live broadcast management interface is the interface capability of small program live broadcast to provide developers with batch operation of live broadcast room. Developers can batch create live studio, get playback source video, get live studio list, etc.
  • Commodity management interface is the interface capability provided by small program livestreaming for developers to perform batch operations on livestreaming commodities. Developers can add, review, delete and update the batch of goods.

Applets cloud development

Applets payment limit

wx.requestPayment

Initiate wechat Pay. Before calling, you need to apply for access to wechat Pay at the micro program wechat public platform-function-wechat Pay entrance

Object object

attribute type The default value mandatory instructions
timeStamp string is Time stamp, the number of seconds from 00:00:00, January 1, 1970 to the present, the current time
nonceStr string is The value is a random string of up to 32 characters
package string is The value of prepay_id returned by the single interface is submitted in the format of prepay_id=***
signType string MD5 no The value of the signature algorithm should be the same as that of the background order
paySign string is Signature, see wechat Pay document for details
success function no The interface called the callback function successfully
fail function no Interface failed to invoke the callback function
complete function no Callback function at the end of an interface call (executed on success and failure)

Object. signType Valid value

value instructions Minimum version
MD5 This parameter applies only to ports of V2 version
HMAC-SHA256 This parameter applies only to ports of V2 version
RSA This parameter is applicable only to V3 ports

The sample code

wx.requestPayment({
  timeStamp: '',
  nonceStr: '',
  package: '',
  signType: 'MD5',
  paySign: '',
  success (res) { },
  fail (res) { }
})
Copy the code

Applets postMessage restriction

When a web page is sent to the applet postMessage, it fires and receives a message at certain times (applet back, component destruction, share). E.data = {data}, data is an array of postMessage arguments

The main use of wechat applet some capabilities

  • Obtaining User information
  • pay
  • invoice
  • The local store
  • The canvas
  • The subcontract to load
  • Share friends/share moments
  • forwarding
  • collection
  • The message
  • Gets the small program code
  • Get applets link

Through the server interface or in the applets management background “tools” – “Generate URL Scheme” entry can be obtained to open any page of the applets URL Scheme. It is suitable for opening small programs from SMS, email, and external wechat web pages. The value of the scenario for opening applets through URL Scheme is 1065. The generated URL Scheme looks like this:

weixin://dl/business/? t= *TICKET*Copy the code

IOS supports THE recognition of URL schemes, which can be used to access applets in application scenarios such as SMS. Android system does not support direct recognition of URL Scheme, so users cannot open applets normally through Scheme. Developers need to use H5 page transfer, and then jump to Scheme to open applets. Examples of redirect codes are as follows:

location.href = 'weixin://dl/business/? t= *TICKET*'Copy the code

This jump method can be called immediately when the user opens H5 or after the user fires an event.

Call the ceiling

Scheme can be divided into short-term Scheme and long-term Scheme according to whether it is valid by expiration and expiration time:

  1. The maximum number of schemes generated by a single applet per day is 500,000 (including short-term and long-term schemes).
  2. A Scheme that is valid for more than 31 days or that is valid permanently is a long-term Scheme. A single small program can generate a maximum of 100,000 long-term schemes. Exercise caution when invoking a Scheme
  3. A Scheme whose validity period is less than 31 days is a short-term Scheme. There is no upper limit for the short-term Scheme generated by a single applet

Matters needing attention

  1. If you need to open the mini program on the webpage of wechat, please use the wechat open label – mini program jump button. Without the public number, you can also directly use the mini program identity to develop the webpage and skip the mini program without authentication. See the static website jump program of cloud development. Applets that meet the open range can send SMS messages supporting the opening of applets
  2. This function basically covers the current version of wechat users are using, and developers do not need to carry out compatibility with the lower version
  3. Only URL schemes for published applets can be generated
  4. When the user jumps to wechat through the URL Scheme, the system pop-up box may be triggered to ask. If the user chooses not to jump, the mini program cannot be opened. Please properly handle the scenario where the user chooses not to jump
  5. Some browsers restrict the ability to jump to a web page. For details about how to set the jump button on a web page, see the example

Open range

Open for impersonal applets.

The sample code

Example of the use of cloud development static web hosting to build web pages, no public number, just ready to small program and open cloud development. The web page will judge the environment to decide which jump method to adopt. For example, if it is detected in the wechat client, open label jump will be exempted; if it is detected in the external browser or App, URL Scheme will be used to jump small program.

Sample web page address: postpay-2g5hm2oxbbb721a4-1258211818.tcloudbaseapp.com/jump-mp.htm…

Detailed code examples and description: cloud development static site jump small procedures

  • The data analysis