SuperAPI AI Directory

mpx-rn-dev-guide

General & other

View repository

Updated 10-16 09:54

About this skill

Mpx Cross-Platform Output to RN Development and Adaptation Guide

Background Introduction

Mpx is a cross-platform development framework based on WeChat Mini Program syntax with Vue-like syntax extension support, enabling the same codebase to be output to Mini Programs (WeChat, Alipay, Baidu, etc.), Web, and React Native platforms. Mpx comprehensively bridges cross-platform development capabilities including templates, scripts, styles, and JSON configuration at compile time and runtime, but when outputting to RN there are still certain capability differences compared with Mini Program and Web platforms.

This SKILL targets the following two types of tasks:

  1. Task One: RN cross-platform adaptation refactoring of existing Mpx components (already written based on Mini Program specifications and needing RN compatibility to be completed).
  2. Task Two: Creating from scratch an Mpx component conforming to RN cross-platform compatibility specifications.

Knowledge Base Index

Knowledge Base Description
Mpx Single-File Component Basic structure and syntax of Mpx single-file components; read before developing any .mpx file
Conditional Compilation Conditional compilation syntax for different parts such as templates, scripts, styles, and JSON; read when encountering cases that cannot be implemented equivalently across platforms and need platform-specific handling
Cross-Platform Output to RN Template Capability Reference Details of cross-platform capabilities for the template part: data binding, template directives, events, Slot, WXML templates, i18n, accessibility, basic component list and the support status of their properties/events
Cross-Platform Output to RN Script Capability Reference Details of cross-platform capabilities for the script part: construction options, lifecycle, instance methods/properties, Composition API, runtime exports, state management
Cross-Platform Output to RN Style Capability Reference Details of cross-platform capabilities for the style part: selectors, units, colors, text inheritance, CSS variables, media queries, animations, background images, and the support status of individual style properties
Best Practices for Cross-Platform Output to RN Style Development Cross-platform compatibility solutions for commonly used selectors and style properties; consult first when encountering style approaches that RN does not support or that behave inconsistently
Cross-Platform Output to RN Environment API Reference @mpxjs/api-proxy Cross-platform support status of the environment APIs provided, involving network, storage, interface, device, media, location, etc.
Cross-Platform Output to RN JSON Configuration Reference Support scope and differences of the three-level JSON configuration for applications, pages, and components on the RN platform
Mixed Development of Mpx and RN Within .mpx , the ways to directly use React Native components and Hooks, and cross-platform isolation solutions

Knowledge Base Usage Recommendations

The reference documentation is relatively large in volume;do not pre-read all references at once, just use them on demand:

  1. For the entry point, only read this SKILL.md: Reading this document completely (including the general constraints and task flow below) is sufficient to cover judgments for 80% of common scenarios; do not pre-read the references directory before starting to write.
  2. Triggered reading: read only when the task flow or general constraintsexplicitly point toa certain reference, and read only the sections relevant to the current issue (reference documents all contain a table of contents and section anchors; use grep / anchor-based skimming, do not Read the entire file).
  3. Minimal reading set for typical tasks(supplement only when this SKILL.md alone is insufficient to judge):
    • Adapting an existing component for RN cross-platform compatibility: after identifying the issue dimension, read the relevant sections of the corresponding capability reference; usually 1–2 are sufficient (e.g., style adaptation mainly consults rn-style-practice.md)。
    • Creating a new RN cross-platform compatible component: start with the general constraints in this SKILL.md, and when uncertain about a capability (whether a property is supported, whether an API exists), consult the corresponding reference on demand.
    • Troubleshooting a specific compilation error: go directly to the relevant section of the capability reference for the error dimension.
  4. When to read single-file-component.md: read only when unfamiliar with the basic structure of Mpx SFC; if already familiar with SFC syntax, you may skip it.

General constraints and adaptation principles

Whether adapting for compatibility or creating new components, cross-platform compatibility must strictly follow the following general constraints:

Template constraints

  1. Basic components first: use the basic components marked as RN-supported and their supported properties/events in Template Capabilities Reference · Basic Components , do not use properties or events not supported by RN; if the user has expanded basic component capabilities through rnConfig.customBuiltInComponents compilation configuration, the user's description prevails.
  2. Page scrolling: RN platform pages are not scrollable by default,onPullDownRefresh / onReachBottom / onPageScroll will not be triggered; when scrolling is needed, use scroll-view to wrap and use its equivalent capabilities.
  3. Event bubbling/capturing: only basic general events (tap / longpress / touchstart / touchmove / touchend / touchcancel) support bubbling and capturing; other events do not. Event delegation should not rely on e.target.dataset, use e.currentTarget instead.
  4. Method calls in templates: template Mustache expressions do not support ordinary method calls; they must be implemented through computed / wxs (except for i18n translation functions).
  5. i18n: in the Composition API, the translation function destructured from useI18n() must be exposed to the template's t / tc / te / tm under its original name return; renaming is prohibited.

Script constraints

  1. Lifecycle / constructor options: use only the lifecycles and constructor options marked as RN-supported in Logic Capabilities Reference ; avoid using RN-unsupported items such as onShareTimeline / onTabItemTap / onAddToFavorites / onSaveExitState .
  2. Environment API: call environment capabilities through the unified @mpxjs/api-proxy provided by mpx.xxx API, avoid directly using wx.xxx / my.xxx; for the specific supported scope see Environment API Reference; if the user has expanded environment API capabilities through custom configuration, the user's description prevails.
  3. selector mapping: selector APIs such as selectComponent / selectAllComponents / createSelectorQuery / createIntersectionObserver in scripts only support #id / .class, and the corresponding template node must declare an empty wx:ref to establish the compile-time selector mapping. For details see Logic Capabilities Reference · Instance Methods and Properties。

Style constraints

  1. Single-class selectors: Do not use selectors not supported by RN, such as compound/pseudo-class/pseudo-element selectors. They must be refactored into single-class equivalent implementations, and the corresponding references in <template> and <script>(such as createSelectorQuery) must be updated accordingly. For common compatibility solutions, see Style Development Best Practices · Selector Usage Recommendations。
    • Bad Example: .list .item { color: red; }
    • Good Example: .list-item { color: red; }
  2. Prefer template directives for dynamic style binding: Use the wx:class / wx:style directive and avoid concatenating class / style interpolation expressions inside the {{}} attribute.
    • Bad Example: <view class="item {{isActive ? 'active' : ''}}">
    • Good Example: <view class="item" wx:class="{{ {active: isActive} }}">
  3. Prefer cross-platform compatible solutions: For common cross-platform compatibility solutions for style properties, see Style Development Best Practices, including:
    • Compound selectors → equivalent single-class selectors
    • Child element pseudo-classes (:first-child , etc.) → wx:class + index conditionals
    • Pseudo-elements (::before / ::after) → replacement with real nodes
    • Active-state pseudo-classes (:active)→ hover-class / hover-stay-time
    • 1rpx ultra-thin lines → hairlineWidth conditional compilation
    • rem / em → rpx
    • Numeric font-weight → normal / bold
    • text overflow → template attribute numberOfLines conditional compilation
    • Hidden elements → zero size + overflow: hidden, avoiding display: none
    • grid / float → Flex layout
  4. Preserve unit comments: Preserve the /*use rpx*/ and /*use px*/ comments in the original styles. During compilation, style units will be switched in batches based on them.

JSON Configuration Constraints

  1. Supported scope: For details on field support for application-, page-, and component-level JSON configurations on the RN platform, see JSON Configuration Reference; unsupported fields (such as tabBar) must be isolated through conditional compilation.
  2. Dynamically generate configuration: When JSON configuration needs to be defined per platform or per environment, use the <script name="json"> form to access __mpx_mode__ / __mpx_env__ variables and generate it dynamically.

Conditional Compilation Constraints

When a capability cannot be equivalently implemented on the RN platform, use conditional compilation for per-platform handling:

  • Original platform condition:__mpx_mode__ === 'wx' || __mpx_mode__ === 'ali' || __mpx_mode__ === 'web'
  • RN platform condition:__mpx_mode__ === 'ios' || __mpx_mode__ === 'android' || __mpx_mode__ === 'harmony'

The following constraints must be followed:

  1. Minimize usage: Reduce the use of conditional compilation when unnecessary to avoid large areas of consecutive conditional compilation harming code readability and later maintainability; conditional compilation should wrap only the incompatible fragments to the minimum extent.
  2. Avoid empty selectors: The output of style conditional compilation must not leave empty selectors (selectors with no style content). The entire rule (including the selector and the contents of the braces) must be wrapped by conditional compilation. For details, see Conditional Compilation · Avoid Empty Selectors in Output。

For complete syntax (styles @mpx-if / templates @mode & @_mode & mpxTagName@mode / scripts __mpx_mode__ / JSON configuration), see Conditional Compilation。

Task 1: Adapt an existing Mpx component for RN cross-platform compatibility

Input

An {name}.mpx component written based on Mini Program technical specifications (already running on Mini Program and Web platforms, but not yet adapted for RN).

Output

Follow the user's instructions; if there are no special instructions, by default use the original file {name}.mpx Make modifications in. When outputting the modified code, output the complete component code, avoid using ellipses, and ensure the user can directly copy or apply the modifications.

Task Workflow

1. Template adaptation and refactoring

  • Read Template Capability Reference, and check one by one the RN support status of the basic components and their properties and events used in <template> .
  • Check whether the dynamic class / style uses {{}} string concatenation, and uniformly refactor it to wx:class / wx:style directive binding.
  • Check whether the nodes referenced by selector-type APIs in <script> declare an empty wx:ref, and those not declared must be completed.
  • For parts that cannot be implemented equivalently, use template conditional compilation(@mode / @_mode / mpxTagName@mode) for platform isolation, and add todo comments to record the reason for the difference.

2. Script adaptation and refactoring

  • Read Logic Capability Reference and Environment API Reference, and check one by one the RN support status of the lifecycle, constructor options, instance methods, and environment API calls in <script> .
  • Platform direct-connect APIs (such as wx.xxx / my.xxx) should be uniformly replaced with mpx.xxx to integrate the implementation smoothed over by @mpxjs/api-proxy .
  • Script logic involving selectors must be refactored to #id / .class syntax, and add an empty wx:ref。
  • For script logic branches not supported by the RN platform, use script conditional compilation for platform isolation, and add todo comments to record the reason for the difference.

3. Style adaptation and refactoring

  1. Expand nested selectors: For preprocessing languages that support nesting, such as sass / less / stylus , first expand and flatten the nested selectors in <style> into traditional selector syntax, to facilitate subsequent compatibility assessment.
    • Bad Example (nesting not expanded):
      .list {
        .item {
          color: red;
          &.active { color: blue; }
        }
      }
      
    • Good Example (nesting expanded):
      .list .item { color: red; }
      .list .item.active { color: blue; }
      
  2. Selector adaptation and refactoring: Read Style Development Best Practices · Selector Usage Recommendations, refactor selectors not supported by RN into cross-platform compatible single-class equivalent implementations, and synchronously update the class name references in <template> and <script> .
  3. Style property adaptation and refactoring: Read Style Capability Reference to check the RN support status of all style properties appearing in <style>、<template>、<script> ; read Style Development Best Practices and refactor them into cross-platform compatible equivalent implementations.
  4. Use conditional compilation for incompatible parts: For selectors or style properties that cannot be implemented equivalently across platforms, use style conditional compilation to minimally wrap theentire rule, keep it in the original platform output artifact, and add todo comments to record the reason for the difference.
    • Good Example (the entire rule is conditionally compiled together to avoid an empty selector):
      /* @mpx-if (__mpx_mode__ === 'wx' || __mpx_mode__ === 'ali' || __mpx_mode__ === 'web') */
      /* todo: RN 不支持 ::-webkit-scrollbar 伪元素 */
      .scroll-view::-webkit-scrollbar { display: none; }
      /* @mpx-endif */
      

4. JSON configuration adaptation and refactoring

  • Read JSON Configuration Reference, check <script type="application/json"> or <script name="json"> whether the fields used are supported on the RN platform.
  • For configuration items with large platform differences, rewrite the JSON block into the <script name="json"> form, using __mpx_mode__ for conditional compilation configuration。

5. Compilation verification

After completing the above modifications, use scripts/compile-validate.js to perform real compilation verification on the modified .mpx files, see compilation verification scriptbelow. If verification fails, return to the corresponding step based on the error category and make corrections.

6. Check and confirmation

Check item by item according to each SFC block, and confirm that conditional compilation and compilation verification have been completed:

Template

  • <template> the basic components, attributes, and events used in Template capability reference are marked as RN-supported, or have been platform-isolated through template conditional compilation; if the user has rnConfig.customBuiltInComponents expanded and extended basic component capabilities through compilation configuration, the user's explanation shall prevail.
  • dynamic class / style has been transformed into the wx:class / wx:style directive, and {{}} concatenation is not used within attribute values.
  • template nodes referenced by selector-type APIs have all declared empty wx:ref to complete compile-time mapping.

Script

  • <script> the lifecycle, constructor options, instance methods, and environment APIs used in Logic capability reference and Environment API reference are marked as RN-supported, or have been platform-isolated through script conditional compilation; if the user has custom expanded and extended environment API capabilities through configuration, the user's explanation shall prevail.
  • platform direct-connection APIs (wx.xxx / my.xxx) have been uniformly replaced with mpx.xxx; selector-type APIs use only the #id / .class syntax.

Style

  • <style> there is no nested selector syntax in
  • <style>、<template>、<script> the selectors and style properties used in Style capability reference are marked as RN-supported, or have been platform-isolated through style conditional compilation.
  • /*use rpx*/ / /*use px*/ unit comments have been retained.

JSON configuration

  • <script type="application/json"> / <script name="json"> the fields used in JSON configuration reference are marked as RN-supported, or have been platform-isolated through configuration conditional compilation.

Conditional compilation

  • there are no large contiguous conditional compilation blocks, only minimal wrapping of incompatible fragments.
  • after style conditional compilation processing, there are no empty selectors in the output.

Local verification

  • passes real compilation verification through the compilation verification script .
  • passes local environment ESLint verification (such as npx eslint path/to/component.mpx), with no lint errors or warnings.

Task 2: Create an Mpx component that conforms to RN cross-platform compatibility specifications

Input

The component requirements described by the user, including view structure, interaction, data sources, target platform scope, and whether React Native native components / Hooks need to be reused, etc.

Output

A complete {name}.mpx component file, with a structure containing <template>、<script>、<style> and a JSON configuration block. The code must directly satisfy the General constraints and adaptation principles, avoiding a round of adaptation modifications after creation.

Task workflow

1. Design phase

  • Align requirement key points with the user: component view structure, props / events, data flow, target platforms, and whether React Native native capabilities are needed.
  • If the component is performance-sensitive or needs to reuse React Native native components / Hooks, read Mpx and RN hybrid development, and determine the platform isolation strategy:
    • Large platform differences: use file-level conditional compilation (hybrid-card.mpx / hybrid-card.ios.mpx), import in a separate file the react-native dependency, to avoid resolution during builds for the original platform.
    • Small local differences: use template/attribute-level conditional compilation (@mode / @_mode / mpxTagName@mode) to isolate RN-specific attributes or a small number of nodes.

2. Implementation phase

Implement in sequence according to the four SFC blocks, following throughout the general constraints and adaptation principles:

3. Compilation verification

Use scripts/compile-validate.js to verify newly created components, see compilation verification scriptbelow. It is recommended to also verify all target platforms (such as --target=wx,ios,web) to ensure cross-platform compatibility.

4. Check and confirm

Reuse the checklist from Task 1 · Check and confirm to confirm that the newly created component does not introduce any RN-incompatible syntax.

Compilation verification script

scripts/compile-validate.js is a real compilation verification tool based on the host project @mpxjs/mpx-cli-service . It automatically probes upward from the input file to the project root directory, loads the project compilation configuration, compiles according to the specified target , and according to style / template / script / json / dependency / other Category aggregation errors and warnings. After modifying or creating components, it is recommended to run this as a mandatory step.

The child component ignore policy automatically switches based on the host project @mpxjs/webpack-plugin version:

  • ≥ 2.10.20 (preferred): via partialCompileRules at the resolver layer, non-target page/component entries are replaced with built-in placeholder implementations.usingComponents declarations are kept in the JSON; if child component path resolution fails, it will still be truthfully exposed as dependency error.
  • < 2.10.20 (compatibility fallback): via a pre-loader that strips the target .mpx entry's usingComponents field before compilation. Cost: loss of dependency resolution and field validation corresponding to the usingComponents field; this is imperfect compatibility; it is recommended to upgrade to ≥ 2.10.20.

Command-line arguments

Argument Default Description
<file.mpx>... - One or more .mpx absolute/relative paths to be validated
--target=<mode> ios Compilation target(s), separate multiple with commas (e.g. wx,ios,web)
--type=<page|component> component Entry type, determines whether to use getPageEntry or getComponentEntry, and affects the partialCompileRules form
--project-root=<path> Auto-detect Explicitly specify the host project root directory
--no-ignore-sub-components Off Disable the default child component placeholder policy and recursively compile all child components
--json Off Output structured JSON results

Exit codes:0 validation passed;1 compilation errors exist;2 runtime exception (e.g. @mpxjs/mpx-cli-service)。

Usage example

# 单组件、默认 target=ios
node .agents/skills/mpx-rn-dev-guide/scripts/compile-validate.js src/components/foo.mpx

# 显式指定为页面(影响 entry 与 partialCompileRules 形态)
node .agents/skills/mpx-rn-dev-guide/scripts/compile-validate.js src/pages/index.mpx --type=page --target=ios

# 跨端多目标校验
node .agents/skills/mpx-rn-dev-guide/scripts/compile-validate.js src/components/foo.mpx --target=wx,ios,web

# 输出结构化 JSON 便于二次处理
node .agents/skills/mpx-rn-dev-guide/scripts/compile-validate.js src/components/foo.mpx --target=ios --json

# 同时递归校验子组件(默认行为是仅校验目标自身)
node .agents/skills/mpx-rn-dev-guide/scripts/compile-validate.js src/components/foo.mpx --target=ios --no-ignore-sub-components

When validation fails, use the error's category field to return to the corresponding task step to locate and fix the problem, and run again until it passes.