background

Since its release last year, The Antmove Applet has thousands of stars on GitHub, with nearly 500 active users in its community, and has helped many applets convert and migrate.

Although Antmove can be implemented on the small program function conversion, because there are some different platforms can not erase the characteristics of the difference, and for specific platforms may have different product requirements, the current user is more common development method is to use Antmove conversion source code, and then the code after the conversion of the second modification.

Although this development mode can achieve user needs to a certain extent, there are several problems:

First, the business still needs to maintain the two sets of code before and after the transformation, the maintenance cost is not controllable, and it is contrary to our original intention of writing at one time and running in multiple places, losing the advantages of transformation;

Second, the user can only use Antmove once to convert from the source code and cannot use the Antmove tool again because the changes to the transform code will be overwritten.

In short, this approach is not optimal in terms of development efficiency and maintainability. In order to solve this problem, Antmove added cross-end grammar and conditional compilation function, users can use cross-end grammar in the small program source code to prepare the logic of a specific platform, combined with Antmove conditional compilation function, only need to maintain a set of source code, can achieve cross-end development. Next, this article will introduce this scheme through a case study.

Across the grammar

Antmove’s cross-side syntax supports use in templates, configurations, scripts, and styles.

Template file

In template files, you can use is-XXX attributes (currently supporting IS-WX, IS-Alipay, IS-Swan, IS-TT, IS-Quick) to distinguish between different platforms. For example,

<text is-wx>This is wechat mini program</text>// Need to compile into wechat applet code<text is-alipay>This is alipay mini program</text>// Need to compile into alipay small program codeCopy the code

Antmove reserves different tags for different platforms.

The script file

In script files, you can use if conditional statements, such as: Wx.__target__ === ‘Alipay’, the wx before the comparison operation represents the platform end of the source code (support wx, Alipay), and the ‘Alipay’ after the comparison operation represents the output platform end (support ‘Alipay’, ‘WX’, ‘TT’, ‘swan ‘, ‘quick’). Use in scripts should be the most common scenario.

/ / the source code
let type = null;
if (wx.__target__ === 'alipay') {
    type = 'alipay';  // Need to compile into alipay small program code
} else {
    type = 'wx';  // Need to compile into wechat applet code
}
Copy the code

The style file

In the style file, you can write styles between /* xxxStart */ and /* xxxEnd */. XXX can be replaced with Wx, Alipay, swan, TT, quick.antmove, which will retain unique styles for different platforms.

/*wxStart*/
.red {
  color: red;
}
/*wxEnd*/

/*alipayStart*/
.green {
  color: green;
}
/*alipayEnd*/
Copy the code

The configuration file

In the configuration file, you can use “_< output platform prefix >Env” as the key (_wxEnv, _alipayEnv, _swanEnv, _quickEnv, _ttEnv) so that different configuration files can be provided for different platforms.

/ / the source code
"_wxEnv": {"window": {
    "backgroundTextStyle": "light"."navigationBarBackgroundColor": "#0068C4"."navigationBarTitleText": "Zhihu micro App"."navigationBarTextStyle": "white"."enablePullDownRefresh": true}},"_alipayEnv": {
  "window": {
    "navigationBarTitleText": Zhihu Alipay Mini Program."navigationBarTextStyle": "white"."enablePullDownRefresh": true}}Copy the code

Antmove recognizes the above cross-end syntax and conditionally compiles to different platforms. More details on cross-end syntax can be found in the AntMove documentation.

Conditional compilation

Antmove conditional compilation is relatively simple to use, taking wechat applets source code as an example, after using cross-end syntax in the source code of wechat applets, execute Antmove -t wx command, you can get clean wechat source code, execute Antmove command, you can conditionally compile to other platforms.

Case study:vant-aliapp

We used Antmove to convert some commonly used wechat applets component libraries, such as Vant/Weui, and released the corresponding version of Alipay applets. In the latest upgrade process, we used Antmove cross-end syntax to modify the source code of Vant 1.6.2, conditional compilation to wechat and Alipay platform.

Ant – Aliapp demo applet

The specific effect can be viewed using alipay scan code

Use cross-end syntax in templates

In general, you don’t need to use cross-side syntax in templates, but it can be useful in some scenarios, such as the public account component that only exists in wechat applets.

<view>
    <view>Wechat public account attention component</view>
    <view>
      <official-account is-wx></official-account>
    </view>
</view>

Copy the code

Use cross-end syntax in scripts: Take the Circle component as an example

The Circle component of Vant uses canvas, while the canvas/SelectorQuery and other interface capabilities of wechat and Alipay are different. Although Antmove has smoothed most of the differences, there are still differences like selectorQuery.in that cannot be smoothed. So we use the cross-end syntax of wx.__target__ in the script to differentiate.

// ...
methods: {
  / /...
  getContext() {
      const {
        type,
        size
      } = this.data;
      if (type === ' ') {
        let ctx = null
        if (wx.__target__ === 'alipay') {
          ctx = wx.createCanvasContext(this.props.id);
        } else {
          ctx = wx.createCanvasContext('van-circle'.this);
        }
        return Promise.resolve(ctx);
      }
      const dpr = wx.getSystemInfoSync().pixelRatio;
      return new Promise((resolve) = > {
        if (wx.__target__ === 'alipay') {
          const ctx = wx.createCanvasContext(this.props.id);
          if (!this.inited) {
            this.inited = true;
            this.setData({
              _size: size * dpr
            })
            ctx.scale(dpr, dpr);
          }
          resolve(ctx);
        } else {
          wx.createSelectorQuery()
            .in(this)
            .select('#van-circle')
            .node()
            .exec((res) = > {
              const canvas = res[0].node;
              const ctx = canvas.getContext(type);
              if (!this.inited) {
                this.inited = true; canvas.width = size * dpr; canvas.height = size * dpr; ctx.scale(dpr, dpr); } resolve(adaptor(ctx)); }); }}); },// ...
}
Copy the code

In the above code, on alipay platform, we directly use the ID on canvas to create canvas Context; on wechat platform, we query the canvas Context with a specific ID in the current customized component. After converting to Alipay using Antmove, we will only keep the code of Alipay:

// ...
methods: {
  / /...
  getContext() {
      const {
        type,
        size
      } = this.data;
      if (type === ' ') {
        let ctx = null
        ctx = wx.createCanvasContext(this.props.id);
        return Promise.resolve(ctx);
      }
      const dpr = wx.getSystemInfoSync().pixelRatio;
      return new Promise((resolve) = > {
        const ctx = wx.createCanvasContext(this.props.id);
          if (!this.inited) {
            this.inited = true;
            this.setData({
              _size: size * dpr
            })
            ctx.scale(dpr, dpr);
          }
          resolve(ctx);
      });
    },
    // ...
}
Copy the code

At the same time, we execute antmove -t wx command to get clean wechat code:

// ...
methods: {
  / /...
  getContext() {
      const {
        type,
        size
      } = this.data;
      if (type === ' ') {
        let ctx = null
        ctx = wx.createCanvasContext('van-circle'.this);
        return Promise.resolve(ctx);
      }
      const dpr = wx.getSystemInfoSync().pixelRatio;
      return new Promise((resolve) = > {
        wx.createSelectorQuery()
            .in(this)
            .select('#van-circle')
            .node()
            .exec((res) = > {
              const canvas = res[0].node;
              const ctx = canvas.getContext(type);
              if (!this.inited) {
                this.inited = true;
                canvas.width = size * dpr;
                canvas.height = size * dpr;
                ctx.scale(dpr, dpr);
              }
              resolve(adaptor(ctx));
            });
      });
    },
    // ...
}
Copy the code

This is just one example of how using cross-end syntax in scripts is particularly useful when implementing different logic for different platforms.

Use a different configuration in app.json

Alipay does not support setting the text color of the navigation bar, but automatically configures it according to the background color of the navigation bar. Therefore, we modify the content of app.json as follows to achieve different navigation bar configuration:

{
  // ...
  "_wxEnv": {
    "window": {
      "navigationBarBackgroundColor": "#f8f8f8"."navigationBarTitleText": "Vant Weapp"."navigationBarTextStyle": "black"."backgroundTextStyle": "dark"."backgroundColor": "#f8f8f8"}},"_alipayEnv": {
    "window": {
      "titleBarColor": "#ffffff"."navigationBarTitleText": "Vant Aliapp"."backgroundColor": "#f8f8f8"}},// ...
}
Copy the code

Other attributes that vary from platform to platform can also be assigned different configurations in this way.

conclusion

Cross-side syntax can be used to smooth out the features of different platforms or to meet product requirements for specific platforms. Compared with modifying the transformed code, it only needs to maintain a set of code, reducing the maintenance cost, so that it can be written once and run in many places.

Cross – end syntax and conditional compilation make Antmove’s cross – end conversion ability more perfect. For some long-established wechat applets with cross-terminal requirements, Antmove is a cross-terminal solution with lower cost in addition to using cross-terminal frameworks such as Taro/UNI-app/RAX to reconstruct or re-develop a set of platform-specific applets.

Finally, Antmove, as the applets conversion project with the longest maintenance time, can be converted from wechat applets to Alipay, Toutiao, Kuaiapp and other terminals with one click. Welcome to exchange and use it.