SuperAPI AI Directory

mpx2rn

Design & creation

View repository

Updated 10-16 03:39

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, capable of outputting the same codebase to Mini Program platforms (WeChat, Alipay, Baidu, etc.), Web, and React Native. Mpx2RN comprehensively bridges the development capabilities across the four major dimensions of templates, scripts, styles, and JSON configuration at compile time and runtime, but there are still certain capability differences compared with Mini Program and Web platforms.

Applicable Scenarios

This SKILL is the unified guide for Mpx2RN development and adaptation, covering the four major dimensions of templates, scripts, styles, and JSON configuration. All Mpx2RN-related tasks should, before starting work, read this SKILL'sGeneral Constraints and Adaptation Principles, including but not limited to:

  • Technical Solution Design: assessing the feasibility of requirements on the RN platform, selection of cross-platform compatibility solutions, whether file-level conditional compilation or hybrid development is needed, etc.;
  • Cross-Platform Adaptation and Refactoring of Legacy Projects: filling in compatibility for existing components already written based on Mini Program specifications but not yet adapted for RN (see belowTask One);
  • Page/Component Development Iterations: writing from scratch or iterating .mpx pages and components that comply with RN cross-platform compatibility specifications (see belowTask Two);
  • Troubleshooting Compile-Time and Runtime Errors: locating RN platform-specific compilation errors (such as empty style selectors, reserved keywords, indentation-sensitive preprocessor errors, etc.) and runtime differences;
  • Code Review: using this SKILL'sGeneral Constraints and Adaptation Principlesas the standard for checking cross-platform compatibility.

Inapplicable Scenarios

The following scenarios are unrelated to Mpx2RN andshould not invokethis SKILL:

  • Mpx development issues targeting only Mini Program platforms (WeChat, Alipay, Baidu, etc.);
  • React Native native development issues (pure RN projects not compiled through Mpx);
  • Issues related to Mpx cross-platform output to Web (Mpx2Web).

Knowledge Base Index

Knowledge Base Description
Mpx Single-File Components 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, JSON, etc.; read when encountering situations that cannot be equivalently implemented across platforms and require platform-specific handling
Cross-Platform Output to RN Template Capabilities Reference Details of cross-platform capabilities for the template part: data binding, template directives, events, Slot, WXML templates, i18n, accessibility, list of basic components and their property/event support
Cross-Platform Output to RN Script Capabilities Reference Details of cross-platform capabilities for the script part: constructor options, lifecycle, instance methods/properties, Composition API, runtime exports, state management
Cross-Platform Output to RN Style Capabilities Reference Style cross-platform capability details: selectors, units, colors, text inheritance, CSS variables, media queries, animations, background images, and per-item style property support
Best practices for cross-platform output RN style development Cross-platform compatibility solutions for common selectors and style properties; consult first when encountering style syntax that RN does not support or that behaves inconsistently
Mpx2RN atomic CSS capability reference UnoCSS-based RN atomic class integration, utility classes, variants, directives and variant groups support scope, color opacity constraints, and compilation troubleshooting; read when the project enables atomic classes or the task involves utility classes
Cross-platform output RN environment API reference @mpxjs/api-proxy Cross-platform support status of the provided environment APIs, involving network, storage, UI, device, media, location, etc.
Cross-platform output RN JSON configuration reference Support scope and differences of app, page, and component three-level JSON configuration on the RN platform
Mpx and RN hybrid development In .mpx Ways to directly use React Native components and Hooks and the cross-platform isolation solution within

Knowledge base usage recommendations

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

  1. Entry point reads only this SKILL.md: reading this document completely (including the general constraints and task workflow below) is sufficient to cover the judgment for 80% of common scenarios; do not pre-read the references directory before starting.
  2. Triggered reading: only when the task workflow or general constraintsexplicitly point toa certain reference, and only read the sections relevant to the current issue (the reference documents all contain a table of contents and section anchors; use grep / anchor jumping to skim, do not Read the entire file).
  3. Minimum reading set for typical tasks(supplement only when this SKILL.md can no longer provide a judgment):
    • RN cross-platform adaptation and refactoring of an existing component: after identifying the problem dimensions, read the relevant sections of the corresponding capability reference; usually 1–2 documents are sufficient (e.g., style refactoring 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), then check the corresponding reference.
    • Troubleshooting a specific compilation error: directly locate the relevant section of the capability reference for the error dimension.
    • Using or troubleshooting atomic classes: read rn-atomic-css.md; only when you need to verify the underlying style properties, additionally read rn-style-reference.md, do not pre-read all style references.
  4. When to read single-file-component.md: read only when unfamiliar with the basic structure of Mpx SFC; you can skip it if you are already familiar with SFC syntax.

General constraints and adaptation principles

Whether for adaptation and refactoring, creating new components, or Code Review, cross-platform compatibility must strictly follow the general constraints below:

Cross-platform compatibility constraints

The output code must run normally on both the original platform and the RN platform. When introducing syntax that is "supported by RN but not by the original platform" (such as numberOfLines@ios|android|harmony / hairlineWidth and other RN-equivalent implementations),do not replace the existing syntax of the original platform, but instead:

  • Use conditional compilation to limit that RN syntax to RN platform output (template attribute suffix @ios|android|harmony, style and script @mpx-if wrapping, etc.);
  • Use conditional compilation for synchronization to preserve the original platform's existing syntax and avoid behavior regressions on the original platform introduced by the refactoring.

This principle runs through the four dimensions of template / script / style / JSON. The constraints below and the 'dual-track' item in style constraint #3 are the concrete implementation of this principle.

Template constraints

  1. Basic components first: Use Template capabilities reference · Basic components to identify the basic components marked as supported by RN and their supported properties/events; do not use properties or events that RN does not support. If the user has extended the basic component capabilities through rnConfig.customBuiltInComponents compile configuration, the user's description takes precedence.
  2. Page scrolling: On the RN platform, pages are not scrollable by default, andonPullDownRefresh / onReachBottom / onPageScroll will not be triggered; when scrolling is needed, use scroll-view to wrap and use its equivalent capability.
  3. Event bubbling/capturing: Only basic common events (tap / longpress / touchstart / touchmove / touchend / touchcancel) support bubbling and capturing; other events do not.
  4. Method calls in templates: Template Mustache expressions do not support ordinary method calls; they must be implemented through computed / wxs (except for the i18n translation function).
  5. i18n: In the Composition API, the useI18n() translation function destructured must be exposed to the template's t / tc / te / tm under its original name return; renaming is prohibited.
  6. Event parameter passing: When passing custom parameters to an event handler, prefer the inline event parameter passing syntax (such as bindtap="handleTap('param')") rather than passing parameters through the data- dataset property.
  7. Wrap text with text first: Although the framework supports inserting text directly in view (automatically adding textat compile time), this introduces an extra view level and incurs performance overhead. Prefer using the text component to explicitly wrap text content; for the cross-platform layout alignment solution fortext , see Style development best practices · text cross-platform layout alignment。

Script constraints

  1. Lifecycle / construction options: Only use the lifecycle and construction options marked as supported by RN in Logic capabilities reference ; avoid using RN-unsupported items such as onShareTimeline / onTabItemTap / onAddToFavorites / onSaveExitState .
  2. Environment API: Use the unified @mpxjs/api-proxy provided by mpx.xxx API to call environment capabilities, and avoid directly using wx.xxx / my.xxx; for the specific supported scope, see Environment API reference. If the user has extended the environment API capabilities through custom configuration, the user's description takes precedence.
  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。
  4. Reserved keywords:id / dataset / data are reserved keywords for page/component instances. Any data key mounted on an instance (including props / data / computed / methods / setup return / inject , etc.) must not use these three names as keys; otherwise, a reserved keyword of miniprogram compile-time/runtime error will be triggered. When naming, use semantic aliases (such as itemId / rowData / pageData) instead.

Style constraints

  1. Style capability judgment criteria: The style property support status is based on Style Capability Reference and should not be judged based on RN's native style support capabilities. Mpx2RN has already smoothed over supported shorthand property expansion, CSS variables,calc(), media queries,rpx units, color formats, text inheritance, and other capabilities, which can be used directly without conditional compilation or alternative syntax.

  2. Selector single-class conversion: It is prohibited to use selectors not supported by RN, such as compound/pseudo-class/pseudo-element selectors. They must be refactored into equivalent single-class 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; }
    • Note: A comma-separated parallel form (such as .classA, .classB { ... }) is equivalent to multiple single-class selector rules sharing the same style block. It still falls within the scope ofsingle-class selectorsand does not need to be split or merged into a new single class; it can be used directly.
    • UnoCSS exception: The hover: variant of atomic classes is converted by the compiler into a component hover style, which is not equivalent to writing <style> in .button:hover; ordinary CSS pseudo-classes are still not supported.
  3. Prefer using template directives for dynamic style binding: Use the wx:class / wx:style directive and avoid concatenating class / style attributes with {{}} interpolation expressions.

    • Bad Example: <view class="item {{isActive ? 'active' : ''}}">
    • Good Example: <view class="item" wx:class="{{ {active: isActive} }}">
  4. Prefer cross-platform compatible solutions: For cross-platform compatibility solutions for common style properties, see Style Development Best Practices. The following table distinguishes two types of handling methods:

    • Equivalent replacement(the replacement syntax takes effect on both the original platform and the RN platform and can be used directly across all platforms)
      • Compound selectors → equivalent single-class selectors
      • Child element pseudo-classes (:first-child etc.) → wx:class + index judgment
      • Pseudo-elements (::before / ::after) → real node replacement
      • Pressed-state pseudo-classes (:active)→ hover-class / hover-stay-time
      • rem / em → rpx
      • Numeric font-weight → normal / bold
      • Hide elements: avoid display: none, use zero size + overflow: hidden
      • grid / float → Flex layout
    • Dual-track retention(the original syntax on the original platform is retained using conditional compilation, and an equivalent implementation is added on the RN side;retaining only the RN side is prohibited)
      • Text overflow: retain white-space / text-overflow / overflow: hidden styles on the original platform (wrap the entire rule with style conditional compilation), and implement the equivalent on the RN side through the template attribute numberOfLines@ios|android|harmony Equivalent implementation
      • 1rpx hairline: retain the 1rpx border syntax on the original platform (using style conditional compilation), and use hairlineWidth as the equivalent on the RN side
  5. Retain unit comments: Retain the /*use rpx*/ and /*use px*/ comments in the original styles; during compilation, style units will be switched in batches accordingly.

  6. Atomic CSS: When the project enables UnoCSS or the template uses atomic classes, read Mpx2RN Atomic CSS Capability Reference. Use only the utility classes and variants supported by both the RN preset and the Mpx2RN style compiler; unsupported items will be treated as compilation errors and will not enter the build output. Color transparency uniformly uses bg-red-500/50 and other slash alpha syntax, do not use bg-red-500 bg-opacity-50 and other separate opacity combinations.

JSON configuration constraints

  1. Supported scope: For details on field support for app, 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 generated configuration: When JSON configuration needs to be defined per platform or per environment, use the <script name="json"> form to access the __mpx_mode__ / __mpx_env__ variable for dynamic generation.

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: Conditional compilation is thelast resortfor handling cross-platform incompatibilities, not the preferred solution. Before using conditional compilation, first confirm whether there is a cross-platform compatible approach that does not require conditional compilation (seeStyle development best practicesand the references for each capability). When conditional compilation is needed, wrap only the truly incompatible fragments minimally; do not fork the entire code block with conditional compilation.
  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 content within the braces) must be wrapped together by conditional compilation. See Conditional compilation · Avoid empty selectors in the output。
  3. In indentation-sensitive preprocessors (stylus / sass, etc.), conditional compilation comments must be indented at the same level as the block body they are in: mpx will replace directive comments and unmatched branches with placeholder comments of equal length, and the placeholder comments retain the original indentation. If a directive comment is written flush left inside an indented block, it will truncate the block context and trigger parsing errors such as expected "indent", got "outdent" .
    • Bad Example (flush left): .back-wrapper inside the block, /* @mpx-if ... */ is flush left with no indentation
    • Good Example (same level as properties in the block): /* @mpx-if ... */ is indented in the same column as properties such as position Attributes in the same column are indented together
  4. Each block uses the corresponding conditional compilation syntax: Style conditional compilation uses /* @mpx-if (__mpx_mode__ === ... ) */ comment syntax; template conditional compilation uses the wx:if="{{__mpx_mode__ === ...}}" directive or the @mode / @_mode attribute suffix; script and JSON configuration conditional compilation use if (__mpx_mode__ === ...) conditional statements,avoid misuse, for details see Conditional compilation。

Task 1: Adapt the Mini Program Mpx component for RN cross-platform compatibility

Input

The {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 modify in the original file {name}.mpx . When outputting the modified code, output the complete component code and avoid using ellipses, ensuring the user can directly copy or apply the modifications.

Task flow

1. Template adaptation and refactoring

  • Read Template Capabilities Reference, and for <template> the basic components used in it, their properties and events are checked one by one for RN support.
  • Check whether the dynamic class / style uses {{}} string concatenation, and refactor it uniformly to wx:class / wx:style directive binding.
  • Check whether the nodes referenced by selector-type APIs in <script> declare an empty wx:ref, and any undeclared ones 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 Capabilities Reference and Environment API Reference, and for <script> the lifecycle, constructor options, instance methods, and environment API calls in it are checked one by one for RN support.
  • Platform direct APIs (such as wx.xxx / my.xxx) are uniformly replaced with mpx.xxx accessing @mpxjs/api-proxy shimmed implementations.
  • Script logic involving selectors must be refactored to the #id / .class syntax, and 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 sass / less / stylus and other preprocessor languages that support nested syntax, 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 Capabilities Reference to check the RN support status of all style properties appearing in <style>、<template>、<script> ; read Style Development Best Practices to refactor them into cross-platform-compatible equivalent implementations.
  4. Atomic class adaptation and refactoring: When the project has enabled UnoCSS, read Mpx2RN Atomic CSS Capabilities Reference, and check the utility classes, variants, dynamic class extraction, and color opacity syntax in the template; change utility classes not supported by RN into supported atomic class combinations or ordinary cross-platform styles.
  5. Use conditional compilation for incompatible parts: For selectors, style properties, or atomic classes that cannot be implemented equivalently across platforms, use style conditional compilation to apply minimal wrapping to theentire rule, keep it in the original platform output artifacts, and add todo comments to record the reason for the difference.
    • Good Example (the entire rule is conditionally compiled together to avoid empty selectors):
      /* @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 modification

  • Read JSON configuration reference, check <script type="application/json"> or <script name="json"> the support status on the RN platform of the fields used in .
  • For configuration items with large platform differences, rewrite the JSON block into the <script name="json"> form, using __mpx_mode__ to perform conditional compilation for configuration。

5. Compilation verification

After completing the above modifications, use the compilation verification script included with this skill to perform real compilation verification on the modified .mpx file (located in the skill directory at scripts/compile-validate.js,not under the host project root directory), see the compilation verification scriptbelow. If verification fails, return to the corresponding step according to the error category and fix it.

6. Check and confirmation

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

Cross-platform compatibility

  • The introduced syntax of "supported by RN but not supported by the original platform" has all been restricted to RN output through conditional compilation; the original platform's original syntax has been retained with conditional compilation and has not been replaced or deleted due to RN adaptation.

Template (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 extended the basic component capabilities through rnConfig.customBuiltInComponents compilation configuration, the user's explanation shall prevail.
  • Dynamic class / style has been converted to the wx:class / wx:style directive, and {{}} concatenation is not used within attribute values.
  • The template nodes referenced by selector-type APIs have all declared empty wx:ref to complete compile-time mapping.

Script (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 extended the environment API capabilities through custom configuration, the user's explanation shall prevail.
  • Platform direct-connect APIs (wx.xxx / my.xxx) have been uniformly replaced with mpx.xxx; selector-type APIs use only the #id / .class syntax.
  • The data keys mounted on the instance (props / data / computed / methods / <script setup> of return / inject , etc.) do not use the reserved keywords id / dataset / data。

Style (style)

  • <style> There are no nested selector syntaxes 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.
  • When the project enables UnoCSS, the utility classes and variants in the template are all within the RN support scope marked in atomic CSS capability reference ; dynamic classes can be statically extracted or have been added to safelist; color opacity does not use a separate *-opacity-* combination.
  • /*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 is no large-scale continuous conditional compilation, only minimal wrapping of incompatible fragments.
  • After style conditional compilation processing, there are no empty selectors in the output.
  • The conditional compilation syntax in each block complies with the specification, and there is no misuse (such as using /* @mpx-if */ comment syntax in template blocks, etc.).

Local validation

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

Task 2: Create an Mpx component that complies with RN cross-platform compatibility specifications

Input

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

Output

Complete {name}.mpx component file, with a structure containing <template>、<script>、<style> and JSON configuration blocks. The code must directly satisfy general constraints and adaptation principles, avoiding another round of adaptation refactoring after creation.

Task flow

1. Design phase

  • Align with the user on key requirements: component view structure, props / events, data flow, target platform, and whether RN 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 react-native dependencies in separate files, and avoid parsing 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 sequentially according to the four SFC blocks, following throughout general constraints and adaptation principles:

3. Compilation validation

Use the compilation validation script included with this skill (located in the skill directory at scripts/compile-validate.js,not in the host project root directory) to validate newly created components; see compilation validation scriptbelow. It is recommended to validate all target platforms (such as --target=wx,ios,web) at the same time 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 validation script

Script location: the compilation validation script is distributed together with this skill, located at in the skill directory at scripts/compile-validate.js(that is, <skill-root>/scripts/compile-validate.js); all command examples below use the path pointing to the skill directoryto invoke this script; do not try to find it in the host project root directory or node_modules .

This script performs real compilation validation based on the @mpxjs/mpx-cli-service installed in the host project: it automatically probes upward from the input .mpx file to the host project root directory, loads the project compilation configuration, compiles according to the specified target , and aggregates errors and warnings by style / template / script / json / dependency / other category. After modifying or creating components, it is recommended to run this as a mandatory step.

Command-line parameters

Parameter Default Description
<file.mpx>... - One or more .mpx absolute/relative paths to validate
--target=<mode> ios Compilation targets, separated by commas when there are multiple (such as 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 Turn off the default child component placeholder strategy and recursively compile all child components
--json Off Output structured JSON results

Exit codes:0 validation passed;1 compilation errors exist;2 runtime exception (such as not finding @mpxjs/mpx-cli-service)。

Usage examples

In the examples below, <skill-root> represents the actual installation path of this skill in the host environment (for example .agents/skills/mpx2rn、.claude/skills/mpx2rn or ~/.claude/skills/mpx2rn , etc., subject to the actual installation location); use this absolute path when invoking, and do not look for scripts/compile-validate.js。

# 单组件、默认 target=ios
node <skill-root>/scripts/compile-validate.js src/components/foo.mpx

# 显式指定为页面(影响 entry 与 partialCompileRules 形态)
node <skill-root>/scripts/compile-validate.js src/pages/index.mpx --type=page --target=ios

# 跨端多目标校验
node <skill-root>/scripts/compile-validate.js src/components/foo.mpx --target=wx,ios,web

# 输出结构化 JSON 便于二次处理
node <skill-root>/scripts/compile-validate.js src/components/foo.mpx --target=ios --json

# 同时递归校验子组件(默认行为是仅校验目标自身)
node <skill-root>/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.