WXS (WeiXin Script) is a lightweight, sandboxed scripting language designed exclusively for the view layer in WeChat Mini Programs. It operates alongside WXML to enable dynamic rendering and data transformation directly within templates.
Key Characteristics
- WXS runs independently of the JavaScript execution context and cannot access global JS variables, functions, or Mini Program APIs.
- It does not rely on client-side base library versions and is compatible across all Mini Program runtime environments.
- WXS modules are isolated by design: variables and functions declared inside a module are private unless explicitly exported via
module.exports. - WXS functions cannot serve as event handlers — they are intended solely for expression evaluation and template-level logic.
- Performance varies by platform: on iOS, WXS typically executes significantly faster than JavaScript; on Android, performance is roughly equivalent.
Inline Module Declaration
WXS code can be embedded directly in WXML using the <wxs> tag:
<wxs module="formatter">
var prefix = "WXS";
var suffix = "Engine";
module.exports.full = prefix + " " + suffix;
</wxs>
<view>{{formatter.full}}</view>
Output:
WXS Engine
External Module Usage
WXS logic may also reside in .wxs files. For example:
// utils.wxs
var capitalize = function(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
};
var reverse = function(arr) {
var result = [];
for (var i = arr.length - 1; i >= 0; i--) {
result.push(arr[i]);
}
return result;
};
module.exports = {
upper: capitalize,
reversed: reverse
};
Referenced in WXML:
<wxs src="./utils.wxs" module="util" />
<view>{{util.upper('mini')}}</view>
<view>{{util.reversed([1, 2, 3])}}</view>
Output:
Mini
[3,2,1]
Module Resolution and Sharing
- Modules are resolved via relative paths only.
- Each
.wxsfile is a singleton: rpeeated imports yield the same initialized instance. - Unreferenced modules remain unexecuted — lazy initialization applies.
Example with inter-module dependency:
// helpers.wxs
var helpers = require('./utils.wxs');
module.exports.greet = function(name) {
return "Hello, " + helpers.upper(name) + "!";
};
<wxs src="./helpers.wxs" module="greeting" />
<view>{{greeting.greet('world')}}</view>
Output:
Hello, World!
Syntax and Scoping Rules
- Variable declarations use
var, supporting hoisting. - Undeclared assignments create implicit globals (discouraged).
- Identifiers must begin with a letter or underscore; subsequent characters may include digits.
- Reserved words (e.g.,
if,function,return,typeof) cannot be used as identifiers.
Valid declarations:
var _count = 0;
var isValid = true;
var user_name = "guest";
Supported Operators
| Category | Examples |
|---|---|
| Arithmetic | +, -, *, /, %, ** |
| Assignment | =, +=, <<=, &= |
| Comparison | <, >, <=, >=, ==, !=, ===, !== |
| Logical | &&, ` |
| Bitwise | &, ` |
| Conditional | condition ? a : b |
| Comma | a = 1, b = 2, a + b |
String concatenation uses +, consistent with JS:
var a = "WX";
var b = "S";
console.log(a + b === "WXS"); // true
Control Flow Statements
Conditional Logic
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else {
grade = "C";
}
Switch Statement
Only literal values (string, number) and identifier references are allowed in case clauses:
switch (status) {
case "active":
stateCode = 200;
break;
case 1:
stateCode = 400;
break;
default:
stateCode = 500;
}
Loops
Both for and while loops support break and continue:
var sum = 0;
for (var i = 0; i < 5; i++) {
if (i === 3) break;
sum += i;
}
// sum === 6
Data Types
WXS supports seven primitive and composite types:
number: integers and floats (42,3.14)string: quoted literals ('text',"data")boolean:true,falseobject: key-value collections ({ a: 1, b: 'x' })array: ordered lists ([1, 'two', {}])function: callable entities (function(x) { return x * 2; })date: time instances created viagetDate()regexp: pattern objects viagetRegExp(pattern, flags)
Type introspection is possible through constructor or typeof:
var now = getDate();
console.log(now.constructor === "Date"); // true
console.log(typeof now); // "object"
var nums = [1, 2];
console.log(nums.constructor === "Array"); // true
console.log(typeof nums); // "object"
Built-in Objects
console
Provides log() for debugging output in developer tools.
Math
Standard mathematical constants and functions:
var maxVal = Math.max(5, 12, 3); // 12
var rand = Math.random(); // 0–1 float
JSON
Supports serialization and parsing:
var obj = { id: 1, name: "test" };
var jsonStr = JSON.stringify(obj); // "{\"id\":1,\"name\":\"test\"}"
var parsed = JSON.parse(jsonStr); // { id: 1, name: "test" }
Number, Date, Global
Expose standard static properties (Number.MAX_VALUE, Date.now(), isNaN(), etc.) following ES5 semantics.
Module Export Patterns
Exports may be assigned via object literal or direct property assignment:
// style A
module.exports = {
format: function(s) { return s.trim().toUpperCase(); },
PI: 3.14159
};
// style B
var helper = function(x) { return x + 1; };
module.exports.inc = helper;
module.exports.version = "1.0";
Imported modules expose these exports under the declared module name in WXML.