以下文件组织规范为最佳实践的建议
所有项目源代码请放在项目根目录 src
目录下,项目所需最基本的文件包括 入口文件 以及 页面文件
app.js
src/pages
目录下一个可靠的 Taro 项目可以按照如下方式进行组织
├── config 配置目录
| ├── dev.js 开发时配置
| ├── index.js 默认配置
| └── prod.js 打包时配置
├── src 源码目录
| ├── components 公共组件目录
| ├── pages 页面文件目录
| | ├── index index 页面目录
| | | ├── banner 页面 index 私有组件
| | | ├── index.js index 页面逻辑
| | | └── index.css index 页面样式
| ├── utils 公共方法库
| ├── app.css 项目总通用样式
| └── app.js 项目入口文件
└── package.json
Taro 中普通 JS/TS 文件以小写字母命名,多个单词以下划线连接,例如 util.js
、util_helper.js
Taro 组件文件命名遵循 Pascal 命名法,例如 ReservationCard.jsx
Taro 中普通 JS/TS 文件以 .js
或者 .ts
作为文件后缀
Taro 组件则以 .jsx
或者 .tsx
作为文件后缀,当然这不是强制约束,只是作为一个实践的建议,组件文件依然可以以 .js
或者 .ts
作为文件后缀
在 Taro 中书写 JavaScript 请遵循以下规则
不要混合使用空格与制表符作为缩进
function hello (name) {
console.log('hi', name) // ✓ 正确
console.log('hello', name) // ✗ 错误
}
const id = 1234 // ✗ 错误
const id = 1234 // ✓ 正确
const a = 'a' // ✓ 正确
const a = 'a'; // ✗ 错误
console.log('hello there')
// 如果遇到需要转义的情况,请按如下三种写法书写
const x = 'hello "world"'
const y = 'hello \'world\''
const z = `hello 'world'`
if (user) {
// ✗ 错误
const name = getName()
}
if (user) {
const name = getName() // ✓ 正确
}
if (condition) { ... } // ✓ 正确
if(condition) { ... } // ✗ 错误
function name (arg) { ... } // ✓ 正确
function name(arg) { ... } // ✗ 错误
run(function () { ... }) // ✓ 正确
run(function() { ... }) // ✗ 错误
fn(... args) // ✗ 错误
fn(...args) // ✓ 正确
for (let i = 0 ;i < items.length ;i++) {...} // ✗ 错误
for (let i = 0; i < items.length; i++) {...} // ✓ 正确
if (admin){...} // ✗ 错误
if (admin) {...} // ✓ 正确
getName( name ) // ✗ 错误
getName(name) // ✓ 正确
user .name // ✗ 错误
user.name // ✓ 正确
typeof!admin // ✗ 错误
typeof !admin // ✓ 正确
//comment // ✗ 错误
// comment // ✓ 正确
/*comment*/ // ✗ 错误
/* comment */ // ✓ 正确
const message = `Hello, ${ name }` // ✗ 错误
const message = `Hello, ${name}` // ✓ 正确
// ✓ 正确
const list = [1, 2, 3, 4]
function greet (name, options) { ... }
// ✗ 错误
const list = [1,2,3,4]
function greet (name,options) { ... }
// ✓ 正确
const value = 'hello world'
console.log(value)
// ✗ 错误
const value = 'hello world'
console.log(value)
function foo () {return true} // ✗ 错误
function foo () { return true } // ✓ 正确
if (condition) { return true } // ✓ 正确
function myFunc () /*<NBSP>*/{} // ✗ 错误
const obj = {
foo: 'foo'
,bar: 'bar' // ✗ 错误
}
const obj = {
foo: 'foo',
bar: 'bar' // ✓ 正确
}
console.log('hello') // ✓ 正确
console.
log('hello') // ✗ 错误
console
.log('hello') // ✓ 正确
console.log ('hello') // ✗ 错误
console.log('hello') // ✓ 正确
const obj = { 'key' : 'value' } // ✗ 错误
const obj = { 'key' :'value' } // ✗ 错误
const obj = { 'key':'value' } // ✗ 错误
const obj = { 'key': 'value' } // ✓ 正确
当前作用域不需要改变的变量使用
const
,反之则使用let
const a = 'a'
a = 'b' // ✗ 错误,请使用 let 定义
let test = 'test'
var noVar = 'hello, world' // ✗ 错误,请使用 const/let 定义变量
// ✓ 正确
const silent = true
let verbose = true
// ✗ 错误
const silent = true, verbose = true
// ✗ 错误
let silent = true,
verbose = true
let name = 'John'
let name = 'Jane' // ✗ 错误
let name = 'John'
name = 'Jane' // ✓ 正确
let name = undefined // ✗ 错误
let name
name = 'value' // ✓ 正确
function my_function () { } // ✗ 错误
function myFunction () { } // ✓ 正确
const my_var = 'hello' // ✗ 错误
const myVar = 'hello' // ✓ 正确
function myFunction () {
const result = something() // ✗ 错误
}
name = name // ✗ 错误
const discount = .5 // ✗ 错误
const discount = 0.5 // ✓ 正确
// ✓ 正确
const x = 2
const message = 'hello, ' + name + '!'
// ✗ 错误
const x=2
const message = 'hello, '+name+'!'
const message = 'Hello \
world' // ✗ 错误
if (price === NaN) { } // ✗ 错误
if (isNaN(price)) { } // ✓ 正确
typeof name === undefined // ✗ 错误
typeof name === 'undefined' // ✓ 正确
const person = {
set name (value) { // ✗ 错误
this._name = value
}
}
const person = {
set name (value) {
this._name = value
},
get name () { // ✓ 正确
return this._name
}
}
const nums = new Array(1, 2, 3) // ✗ 错误
const nums = [1, 2, 3] // ✓ 正确
const { a: {} } = foo // ✗ 错误
const { a: { b } } = foo // ✓ 正确
const user = {
name: 'Jane Doe',
name: 'John Doe' // ✗ 错误
}
Object.prototype.age = 21 // ✗ 错误
let score = 100
function game () {
score: while (true) { // ✗ 错误
score -= 10
if (score > 0) continue score
break
}
}
const user = {
name: 'Jane Doe', age: 30,
username: 'jdoe86' // ✗ 错误
}
const user = { name: 'Jane Doe', age: 30, username: 'jdoe86' } // ✓ 正确
const user = {
name: 'Jane Doe',
age: 30,
username: 'jdoe86'
}
const user = { ['name']: 'John Doe' } // ✗ 错误
const user = { name: 'John Doe' } // ✓ 正确
function foo (n) {
if (n <= 0) return
arguments.callee(n - 1) // ✗ 错误
}
function foo (n) {
if (n <= 0) return
foo(n - 1)
}
function sum (a, b, a) { // ✗ 错误
// ...
}
function sum (a, b, c) { // ✓ 正确
// ...
}
const name = function () {
getName()
}.bind(user) // ✗ 错误
const name = function () {
this.getName()
}.bind(user) // ✓ 正确
eval( "var result = user." + propName ) // ✗ 错误
const result = user[propName] // ✓ 正确
const myFunc = (function () { }) // ✗ 错误
const myFunc = function () { } // ✓ 正确
function myFunc () { }
myFunc = myOtherFunc // ✗ 错误
setTimeout("alert('Hello world')") // ✗ 错误
setTimeout(function () { alert('Hello world') }) // ✓ 正确
if (authenticated) {
function setAuthUser () {} // ✗ 错误
}
const sum = new Function('a', 'b', 'return a + b') // ✗ 错误
let config = new Object() // ✗ 错误
const getName = function () { }() // ✗ 错误
const getName = (function () { }()) // ✓ 正确
const getName = (function () { })() // ✓ 正确
使用
Promise
或者async functions
来实现异步编程
function* helloWorldGenerator() { // ✗ 错误
yield 'hello';
yield 'world';
return 'ending';
}
const pattern = /\x1f/ // ✗ 错误
const pattern = /\x20/ // ✓ 正确
const regexp = /test value/ // ✗ 错误
const regexp = /test {3}value/ // ✓ 正确
const regexp = /test value/ // ✓ 正确
class animal {}
const dog = new animal() // ✗ 错误
class Animal {}
const dog = new Animal() // ✓ 正确
class Dog {}
Dog = 'Fido' // ✗ 错误
class Dog {
constructor () {
super() // ✗ 错误
}
}
class Dog extends Mammal {
constructor () {
super() // ✓ 正确
}
}
class Dog extends Animal {
constructor () {
this.legs = 4 // ✗ 错误
super()
}
}
class Car {
constructor () { // ✗ 错误
}
}
class Car {
constructor () { // ✗ 错误
super()
}
}
class Dog {
bark () {}
bark () {} // ✗ 错误
}
function Animal () {}
const dog = new Animal // ✗ 错误
const dog = new Animal() // ✓ 正确
new Character() // ✗ 错误
const character = new Character() // ✓ 正确
import { myFunc1 } from 'module'
import { myFunc2 } from 'module' // ✗ 错误
import { myFunc1, myFunc2 } from 'module' // ✓ 正确
import { config as config } from './config' // ✗ 错误
import { config } from './config' // ✓ 正确
function sum (a, b) {
return result = a + b // ✗ 错误
}
with (val) {...} // ✗ 错误
label:
while (true) {
break label // ✗ 错误
}
let undefined = 'value' // ✗ 错误
function doSomething () {
return true
console.log('never called') // ✗ 错误
}
例外: obj == null 可以用来检查 null || undefined
if (name === 'John') // ✓ 正确
if (name == 'John') // ✗ 错误
if (name !== 'John') // ✓ 正确
if (name != 'John') // ✗ 错误
if (score === score) {} // ✗ 错误
// ✓ 正确
if (condition) {
// ...
} else {
// ...
}
// ✗ 错误
if (condition)
{
// ...
}
else
{
// ...
}
// ✓ 正确
if (options.quiet !== true) console.log('done')
// ✓ 正确
if (options.quiet !== true) {
console.log('done')
}
// ✗ 错误
if (options.quiet !== true)
console.log('done')
// ✓ 正确
const location = env.development ? 'localhost' : 'www.api.com'
// ✓ 正确
const location = env.development
? 'localhost'
: 'www.api.com'
// ✗ 错误
const location = env.development ?
'localhost' :
'www.api.com'
if (42 === age) { } // ✗ 错误
if (age === 42) { } // ✓ 正确
if (false) { // ✗ 错误
// ...
}
if (x === 0) { // ✓ 正确
// ...
}
while (true) { // ✓ 正确
// ...
}
for (let i = 0; i < items.length; j++) {...} // ✗ 错误
for (let i = 0; i < items.length; i++) {...} // ✓ 正确
let score = val ? val : 0 // ✗ 错误
let score = val || 0 // ✓ 正确
switch (id) {
case 1:
// ...
case 1: // ✗ 错误
}
switch (filter) {
case 1:
doSomething() // ✗ 错误
case 2:
doSomethingElse()
}
switch (filter) {
case 1:
doSomething()
break // ✓ 正确
case 2:
doSomethingElse()
}
switch (filter) {
case 1:
doSomething()
// fallthrough // ✓ 正确
case 2:
doSomethingElse()
}
const result = true
if (!!result) { // ✗ 错误
// ...
}
const result = true
if (result) { // ✓ 正确
// ...
}
if (doSomething(), !!test) {} // ✗ 错误
// ✓ 正确
run(function (err) {
if (err) throw err
window.alert('done')
})
// ✗ 错误
run(function (err) {
window.alert('done')
})
try {
// ...
} catch (e) {
e = 'new value' // ✗ 错误
}
try {
// ...
} catch (e) {
const newVal = 'new value' // ✓ 正确
}
throw 'error' // ✗ 错误
throw new Error('error') // ✓ 正确
try {
// ...
} catch (e) {
// ...
} finally {
return 42 // ✗ 错误
}
asyncTask('google.com').catch(err => console.log(err)) // ✓ 正确
Taro 中组件以类的形式进行创建,并且单个文件中只能存在单个组件
使用两个空格进行缩进,不要混合使用空格与制表符作为缩进
import Taro, { Component } from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
class MyComponent extends Component {
render () {
return (
<View className='test'> // ✓ 正确
<Text>12</Text> // ✗ 错误
</View>
)
}
}
JSX 属性均使用单引号
import Taro, { Component } from '@tarojs/taro'
import { View, Input } from '@tarojs/components'
class MyComponent extends Component {
render () {
return (
<View className='test'> // ✓ 正确
<Text className="test_text">12</Text> // ✗ 错误
</View>
)
}
}
多个属性,多行书写,每个属性占用一行,标签结束另起一行
// bad
<Foo superLongParam='bar'
anotherSuperLongParam='baz' />
// good
<Foo
superLongParam='bar'
anotherSuperLongParam='baz'
/>
// 如果组件的属性可以放在一行就保持在当前一行中
<Foo bar='bar' />
// 多行属性采用缩进
<Foo
superLongParam='bar'
anotherSuperLongParam='baz'
>
<Quux />
</Foo>
终始在自闭合标签前面添加一个空格
// bad
<Foo/>
// very bad
<Foo />
// bad
<Foo
/>
// good
<Foo />
属性名称始终使用驼峰命名法
// bad
<Foo
UserName='hello'
phone_number={12345678}
/>
// good
<Foo
userName='hello'
phoneNumber={12345678}
/>
用括号包裹多行 JSX 标签
// bad
render () {
return <MyComponent className='long body' foo='bar'>
<MyChild />
</MyComponent>
}
// good
render () {
return (
<MyComponent className='long body' foo='bar'>
<MyChild />
</MyComponent>
);
}
// good
render () {
const body = <div>hello</div>
return <MyComponent>{body}</MyComponent>
}
当标签没有子元素时,始终时候自闭合标签
// bad
<Foo className='stuff'></Foo>
// good
<Foo className='stuff' />
如果控件有多行属性,关闭标签要另起一行
// bad
<Foo
bar='bar'
baz='baz' />
// good
<Foo
bar='bar'
baz='baz'
/>
在 Taro 组件中会包含类静态属性、类属性、生命周期等的类成员,其书写顺序最好遵循以下约定(顺序从上至下)
onClickSubmit()
或者 onChangeDescription()
import Taro, { Component } from '@tarojs/taro'
import { View } from '@tarojs/components'
class MyComponent extends Component {
render () {
return (
<View className='test'> // ✓ 正确
<Text>12</Text> // ✗ 错误
</View>
)
}
}
import Taro, { Component } from '@tarojs/taro'
import { View, Input } from '@tarojs/components'
class MyComponent extends Component {
state = {
myTime: 12
}
render () {
const { isEnable } = this.props // ✓ 正确
const { myTime } = this.state // ✓ 正确
return (
<View className='test'>
{isEnable && <Text className='test_text'>{myTime}</Text>}
</View>
)
}
}
<Hello class='foo' /> // ✗ 错误
<Hello id='foo' /> // ✗ 错误
<Hello style='foo' /> // ✗ 错误
<div className='foo'></div> // ✗ 错误
<span id='foo' /></span> // ✗ 错误
由于 this.setState 异步的缘故,这样的做法会导致一些错误,可以通过给 this.setState 传入函数来避免
this.setState({
value: this.state.value + 1
}) // ✗ 错误
this.setState(prevState => ({ value: prevState.value + 1 })) // ✓ 正确
list.map(item => {
return (
<View className='list_item' key={item.id}>{item.name}</View>
)
})
因为在
componentDidMount
中调用this.setState
会导致触发更新
import Taro, { Component } from '@tarojs/taro'
import { View, Input } from '@tarojs/components'
class MyComponent extends Component {
state = {
myTime: 12
}
componentDidMount () {
this.setState({ // ✗ 尽量避免,可以在 componentWillMount 中处理
name: 1
})
}
render () {
const { isEnable } = this.props
const { myTime } = this.state
return (
<View className='test'>
{isEnable && <Text className='test_text'>{myTime}</Text>}
</View>
)
}
}
import Taro, { Component } from '@tarojs/taro'
import { View, Input } from '@tarojs/components'
class MyComponent extends Component {
state = {
myTime: 12
}
componentWillUpdate () {
this.setState({ // ✗ 错误
name: 1
})
}
componentDidUpdate () {
this.setState({ // ✗ 错误
name: 1
})
}
render () {
const { isEnable } = this.props
const { myTime } = this.state
this.setState({ // ✗ 错误
name: 11
})
return (
<View className='test'>
{isEnable && <Text className='test_text'>{myTime}</Text>}
</View>
)
}
}
import Taro, { Component } from '@tarojs/taro'
import { View, Input } from '@tarojs/components'
class MyComponent extends Component {
state = {
myTime: 12,
noUsed: true // ✗ 没有用到
}
render () {
const { myTime } = this.state
return (
<View className='test'>
<Text className='test_text'>{myTime}</Text>
</View>
)
}
}
import Taro, { Component } from '@tarojs/taro'
import { View, Input } from '@tarojs/components'
class MyComponent extends Component {
static defaultProps = {
isEnable: true
}
state = {
myTime: 12
}
render () {
const { isEnable } = this.props
const { myTime } = this.state
return (
<View className='test'>
{isEnable && <Text className='test_text'>{myTime}</Text>}
</View>
)
}
}
import Taro, { Component } from '@tarojs/taro'
import { View, Input } from '@tarojs/components'
class MyComponent extends Component {
state = {
myTime: 12
}
render () { // ✗ 没有返回值
const { isEnable } = this.props
const { myTime } = this.state
<View className='test'>
{isEnable && <Text className="test_text">{myTime}</Text>}
</View>
}
}
<Hello personal />
<Hello personal={false} />
属性书写不带空格,如果属性是一个对象,则对象括号旁边需要带上空格
<Hello name={ firstname } /> // ✗ 错误
<Hello name={ firstname} /> // ✗ 错误
<Hello name={firstname } /> // ✗ 错误
<Hello name={{ firstname: 'John', lastname: 'Doe' }} /> // ✓ 正确
在 Taro 中所有默认事件如
onClick
、onTouchStart
等等,均以on
开头
import Taro, { Component } from '@tarojs/taro'
import { View, Input } from '@tarojs/components'
class MyComponent extends Component {
state = {
myTime: 12
}
clickHandler (e) {
console.log(e)
}
render () {
const { myTime } = this.state
return (
<View className='test' onClick={this.clickHandler}> // ✓ 正确
<Text className='test_text'>{myTime}</Text>
</View>
)
}
}
import Taro, { Component } from '@tarojs/taro'
import { View, Input } from '@tarojs/components'
import Tab from '../../components/Tab/Tab'
class MyComponent extends Component {
state = {
myTime: 12
}
clickHandler (e) {
console.log(e)
}
render () {
const { myTime } = this.state
return (
<View className='test'>
<Tab onChange={this.clickHandler} /> // ✓ 正确
<Text className='test_text'>{myTime}</Text>
</View>
)
}
}
以下代码会被 ESLint 提示警告,同时在 Taro(小程序端)也不会有效:
numbers.map((number) => {
let element = null
const isOdd = number % 2
if (isOdd) {
element = <Custom />
}
return element
})
以下代码不会被警告,也应当在 Taro 任意端中能够运行:
numbers.map((number) => {
let isOdd = false
if (number % 2) {
isOdd = true
}
return isOdd && <Custom />
})
解决方案
尽量在 map 循环中使用条件表达式或逻辑表达式
numbers.map((number) => {
const isOdd = number % 2
return isOdd ? <Custom /> : null
})
numbers.map((number) => {
const isOdd = number % 2
return isOdd && <Custom />
})
Taro 在小程序端实际上把 JSX 转换成了字符串模板,而一个原生 JSX 表达式实际上是一个 React/Nerv 元素(react-element)的构造器,因此在原生 JSX 中你可以随意地对一组 React 元素进行操作。但在 Taro 中你只能使用
map
方法,Taro 转换成小程序中wx:for
以下代码会被 ESLint 提示警告,同时在 Taro(小程序端)也不会有效:
test.push(<View />)
numbers.forEach(number => {
if (someCase) {
a = <View />
}
})
test.shift(<View />)
components.find(component => {
return component === <View />
})
components.some(component => component.constructor.__proto__ === <View />.constructor)
以下代码不会被警告,也应当在 Taro 任意端中能够运行:
numbers.filter(Boolean).map((number) => {
const element = <View />
return <View />
})
解决方案
先处理好需要遍历的数组,然后再用处理好的数组调用 map
方法。
numbers.filter(isOdd).map((number) => <View />)
for (let index = 0; index < array.length; index++) {
// do you thing with array
}
const element = array.map(item => {
return <View />
})
以下代码会被 ESLint 提示警告,同时在 Taro(小程序端)也不会有效:
<View onClick={() => this.handleClick()} />
<View onClick={(e) => this.handleClick(e)} />
<View onClick={() => ({})} />
<View onClick={function () {}} />
<View onClick={function (e) {this.handleClick(e)}} />
以下代码不会被警告,也应当在 Taro 任意端中能够运行:
<View onClick={this.hanldeClick} />
<View onClick={this.props.hanldeClick} />
<View onClick={this.hanldeClick.bind(this)} />
<View onClick={this.props.hanldeClick.bind(this)} />
解决方案
<View onClick={this.props.hanldeClick.bind(this)} />
以下代码会被 ESLint 提示警告,同时在 Taro(小程序端)也不会有效:
<Custom child={<View />} />
<Custom child={() => <View />} />
<Custom child={function () { <View /> }} />
<Custom child={ary.map(a => <View />)} />
解决方案
通过 props 传值在 JSX 模板中预先判定显示内容
以下代码会被 ESLint 提示警告,同时在 Taro(小程序端)也不会有效:
<View {...this.props} />
<View {...props} />
<Custom {...props} />
以下代码不会被警告,也应当在 Taro 任意端中能够运行:
const { id, ...rest } = obj
const [ head, ...tail] = array
const obj = { id, ...rest }
解决方案
除非微信小程序开放更多能力,目前看不到能支持该特性的可能性
以下代码会被 ESLint 提示警告,同时在 Taro(小程序端)也不会有效:
function Test () {
return <View />
}
function Test (ary) {
return ary.map(() => <View />)
}
const Test = () => {
return <View />
}
const Test = function () {
return <View />
}
以下代码不会被警告,也应当在 Taro 任意端中能够运行:
class App extends Component {
render () {
return (
<View />
)
}
}
解决方案
使用 class
定义组件