Taro 学习日志

Taro 是一套遵循 React 语法规范的 多端开发 解决方案。
使用 Taro,我们可以只书写一套代码,再通过 Taro 的编译工具,将源代码分别编译出可以在不同端(微信/百度/支付宝/字节跳动/QQ小程序、快应用、H5、React-Native 等)运行的代码。

快速开始

安装

Taro 项目基于 node,请确保已具备较新的 node 环境(>=8.0.0),推荐使用 node 版本管理工具 nvm 来管理 node,这样不仅可以很方便地切换 node 版本,而且全局安装时候也不用加 sudo 了。

CLI 工具安装

首先,你需要使用 npm 或者 yarn 全局安装 @tarojs/cli,或者直接使用npx:

1
2
3
4
5
6
7
8
# 使用 npm 安装 CLI
$ npm install -g @tarojs/cli

# OR 使用 yarn 安装 CLI
$ yarn global add @tarojs/cli

# OR 安装了 cnpm,使用 cnpm 安装 CLI
$ cnpm install -g @tarojs/cli
  • 安装完成
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$ taro --help
👽 Taro v1.3.19

Usage: taro <command> [options]

Options:
-V, --version output the version number
-h, --help output usage information

Commands:
init [projectName] Init a project with default templete
config <cmd> Taro config
create Create page for project
build Build a project with options
update Update packages of taro
convert Convert weapp to taro
info Diagnostics Taro env info
doctor Diagnose taro project
help [cmd] display help for [cmd]

注意事项

如果安装过程出现sass相关的安装错误,请在安装mirror-config-china后重试。

1
npm install -g mirror-config-china

项目初始化

使用命令创建模板项目

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
taro init TaroApp

$ taro init TaroApp
👽 Taro v1.3.19

Taro即将创建一个新项目!
Need help? Go and open issue: https://github.com/NervJS/taro/issues/new

? 请输入项目介绍! Taro Test
? 请输入项目介绍! Taro Test
? 是否需要使用 TypeScript ? (Y/n) Y
? 是否需要使用 TypeScript ? Yes
? 请选择 CSS 预处理器(Sass/Less/Stylus) (Use arrow keys)
? 请选择 CSS 预处理器(Sass/Less/Stylus) Sass
? 请选择模板 (Use arrow keys)
? 请选择模板 默认模板

✔ 创建项目: TaroApp
✔ 创建文件: TaroApp\.npmrc
✔ 创建文件: TaroApp\.editorconfig
✔ 创建文件: TaroApp\.eslintrc
✔ 创建文件: TaroApp\.gitignore
...
创建项目 TaroApp 成功!
请进入项目目录 TaroApp 开始工作吧!😝

npm 5.2+ 也可在不全局安装的情况下使用 npx 创建模板项目

1
npx @tarojs/cli init TaroApp

在创建完项目之后,Taro 会默认开始安装项目所需要的依赖,安装使用的工具按照 yarn>cnpm>npm 顺序进行检测,一般来说,依赖安装会比较顺利,但某些情况下可能会安装失败,这时候你可以在项目目录下自己使用安装命令进行安装

1
2
3
4
5
6
7
8
# 使用 yarn 安装依赖
$ yarn

# OR 使用 cnpm 安装依赖
$ cnpm install

# OR 使用 npm 安装依赖
$ npm install

运行

Taro 需要运行不同的命令,将 Taro 代码编译成不同端的代码,然后在对应的开发工具中查看效果。

微信小程序

微信小程序编译预览及打包(去掉 –watch 将不会监听文件修改,并会对代码进行压缩打包)

  • yarn
1
2
yarn dev:weapp
yarn build:weapp
  • npm
1
2
npm run dev:weapp
npm run build:weapp
  • taro
1
2
3
// 仅限全局安装
taro build --type weapp --watch
taro build --type weapp
  • npx
1
2
npx taro build --type weapp --watch
npx taro build --type weapp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$ taro build --type weapp
👽 Taro v1.3.19

开始编译项目 TaroApp
生成 工具配置 dist/project.config.json
编译 入口文件 src/app.tsx
拷贝 NPM文件 dist/npm/@tarojs/taro-weapp/npm/@tarojs/taro/dist/index.js
拷贝 NPM文件 dist/npm/@tarojs/taro-weapp/npm/@tarojs/taro/index.js
拷贝 NPM文件 dist/npm/@tarojs/taro-weapp/dist/index.js
拷贝 NPM文件 dist/npm/@tarojs/taro-weapp/index.js
生成 入口配置 dist/app.json
生成 入口文件 dist/app.js
生成 入口样式 dist/app.wxss
编译 所有页面
编译 页面文件 src/pages/index/index
生成 页面配置 dist/pages/index/index.json
生成 页面逻辑 dist/pages/index/index.js
生成 页面模板 dist/pages/index/index.wxml
生成 页面样式 dist/pages/index/index.wxss

常用CLI命令

  • 查看 Taro 所有命令及帮助
1
taro --help
  • 更新Taro CLI工具
1
2
3
4
5
6
7
8
# taro
$ taro update self

# npm
npm i -g @tarojs/cli@latest

# yarn
yarn global add @tarojs/cli@latest
  • 更新项目中Taro相关的依赖
1
taro update project
  • 环境及依赖检测
1
2
3
4
5
6
7
8
9
10
$ taro info
👽 Taro v1.3.19


Taro CLI 1.3.19 environment info:
System:
OS: Windows 10
Binaries:
Node: 8.12.0 - D:\nodeJs\node.EXE
npm: 6.9.0 - D:\nodeJs\npm.CMD
  • Taro Doctor
1
taro doctor

其他常见问题

回到某个版本

需要安装某个固定版本,或者回到某个版本,例如我们要安装 1.3.9 , 则如下:

1
2
3
4
5
6
7
8
# 使用 npm 安装 CLI
$ npm install -g @tarojs/cli@1.3.9

# OR 使用 yarn 安装 CLI
$ yarn global add @tarojs/cli@1.3.9

# OR 安装了 cnpm,使用 cnpm 安装 CLI
$ cnpm install -g @tarojs/cli@1.3.9

CLI 配置

1.3.9 开始 Taro 会在用户根目录下创建 .taro 文件夹,其中 .taro/index.json 用于存放 CLI 相关配置。

开发者可以使用 taro config 命令对配置项进行一系列操作:

  • 查看用法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
$ taro config --help
👽 Taro v1.3.19

Usage: taro-config [options]

Options:
--json 以 JSON 形式输出
-h, --help output usage information

Synopsis:
$ taro config set <key> <value>
$ taro config get <key>
$ taro config delete <key>
$ taro config list [--json]
  • 设置配置项的值为
1
2
$ taro config set key_taro value_taro
👽 Taro v1.3.19
  • 读取配置项
1
2
3
4
$ taro config get key_taro
👽 Taro v1.3.19

value_taro
  • 删除配置项
1
2
$ taro config delete key_taro
👽 Taro v1.3.19
  • 打印所有配置项
1
2
3
4
5
6
7
8
9
10
11
$ taro config list
👽 Taro v1.3.19

templateSource=github:NervJS/taro-project-templates

$ taro config list --json
👽 Taro v1.3.19

{
"templateSource": "github:NervJS/taro-project-templates"
}

基础教程

目录结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
├── 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规范

文件命名

Taro 中普通 JS/TS 文件以小写字母命名,多个单词以下划线连接,例如 util.jsutil_helper.js

Taro 组件文件命名遵循 Pascal 命名法,例如 ReservationCard.jsx

文件后缀

Taro 中普通 JS/TS 文件以 .js 或者 .ts 作为文件后缀

Taro 组件则以 .jsx 或者 .tsx 作为文件后缀,当然这不是强制约束,只是作为一个实践的建议,组件文件依然可以以 .js 或者 .ts 作为文件后缀

JavaScript 书写规范

在 Taro 中书写 JavaScript 请遵循以下规则…

Taro框架

项目目录结构

1
2
3
4
5
6
7
8
9
10
11
12
13
├── dist                   编译结果目录
├── config 配置目录
| ├── dev.js 开发时配置
| ├── index.js 默认配置
| └── prod.js 打包时配置
├── src 源码目录
| ├── pages 页面文件目录
| | ├── index index 页面目录
| | | ├── index.js index 页面逻辑
| | | └── index.css index 页面样式
| ├── app.css 项目总通用样式
| └── app.js 项目入口文件
└── package.json

入口文件

入口文件默认是 src 目录下的 app.js

代码示例

一个普通的入口文件示例如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import Taro, { Component } from '@tarojs/taro'
import Index from './pages/index'

import './app.scss'

class App extends Component {
// 项目配置
config = {
pages: [
'pages/index/index'
],
window: {
backgroundTextStyle: 'light',
navigationBarBackgroundColor: '#fff',
navigationBarTitleText: 'WeChat',
navigationBarTextStyle: 'black'
}
}

componentWillMount () {}

componentDidMount () {}

componentDidShow () {}

componentDidHide () {}

render () {
return (
<Index />
)
}
}

可以看出入口文件也是 React 风格的写法,首先需要引用依赖 @tarojs/taro,这是 Taro 方案的基础框架,在这里我们继承了 Component 组件基类。

路由功能

路由API

Taro 中,路由功能是默认自带的,不需要开发者进行额外的路由配置。

我们只需要在入口文件的 config 配置中指定好 pages,然后就可以在代码中通过 Taro 提供的 API 来跳转到目的页面,例如:

1
2
3
4
5
6
7
8
9
// 跳转到目的页面,打开新页面
Taro.navigateTo({
url: '/pages/page/path/name'
})

// 跳转到目的页面,在当前页面打开
Taro.redirectTo({
url: '/pages/page/path/name'
})

路由传参

我们可以通过在所有跳转的 url 后面添加查询字符串参数进行跳转传参,例如

1
2
3
4
// 传入参数 id=2&type=test
Taro.navigateTo({
url: '/pages/page/path/name?id=2&type=test'
})

这样的话,在跳转成功的目标页的生命周期方法里就能通过 this.$router.params 获取到传入的参数,例如上述跳转,在目标页的 componentWillMount 生命周期里获取入参

1
2
3
4
5
class C extends Taro.Component {
componentWillMount () {
console.log(this.$router.params)
}
}

静态资源引用

引用样式文件

1
2
3
4
5
// 引用CSS文件
import './css/path/name.css'

// 引用SCSS文件
import './css/path/name.scss'

引用 JS 文件

1
2
import { functionName } from './css/path/name.js'
import defaultExportName from './css/path/name.js'

引用图片、音频、字体等文件

1
2
3
4
5
6
7
// 引用文件
import namedPng from '../../images/path/named.png'

// 使用
<View>
<Image src={namedPng} />
</View>

引用 JSON 文件

1
2
3
4
5
6
7
8
9
10
 // 引用 json 文件
/**
* named.json
* {
* x: 1
* }
**/
import namedJson from '../../json/path/named.json'

console.log(namedJson.x)

编译配置

编译配置存放于项目根目录下 config 目录中,包含三个文件

  • index.js 是通用配置
  • dev.js 是项目预览时的配置
  • prod.js 是项目打包时定的配置

index.js - 通用配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
const config = {
// 项目名称
projectName: 'TaroApp',
// 项目创建日期
date: '2019-9-29',
// 设计稿尺寸
designWidth: 750,
deviceRatio: {
'640': 2.34 / 2,
'750': 1,
'828': 1.81 / 2
},
// 项目源码目录
sourceRoot: 'src',
// 项目产出目录
outputRoot: 'dist',
// 通用插件配置
plugins: {
babel: {
sourceMap: true,
presets: [
['env', {
modules: false
}]
],
plugins: [
'transform-decorators-legacy',
'transform-class-properties',
'transform-object-rest-spread'
]
}
},
// 全局变量设置
defineConstants: {
},
// 文件 copy 配置
copy: {
patterns: [
],
options: {
}
},
// 小程序端专用配置
weapp: {
module: {
postcss: {
autoprefixer: {
enable: true,
config: {
browsers: [
'last 3 versions',
'Android >= 4.1',
'ios >= 8'
]
}
},
pxtransform: {
enable: true,
config: {

}
},
// 小程序端样式引用本地资源内联配置
url: {
enable: true,
config: {
limit: 10240 // 设定转换尺寸上限
}
},
cssModules: {
enable: false, // 默认为 false,如需使用 css modules 功能,则设为 true
config: {
namingPattern: 'module', // 转换模式,取值为 global/module
generateScopedName: '[name]__[local]___[hash:base64:5]'
}
}
}
}
},
// H5端专用配置
h5: {
publicPath: '/',
staticDirectory: 'static',
module: {
postcss: {
autoprefixer: {
enable: true,
config: {
browsers: [
'last 3 versions',
'Android >= 4.1',
'ios >= 8'
]
}
},
cssModules: {
enable: false, // 默认为 false,如需使用 css modules 功能,则设为 true
config: {
namingPattern: 'module', // 转换模式,取值为 global/module
generateScopedName: '[name]__[local]___[hash:base64:5]'
}
}
}
}
}
}

module.exports = function (merge) {
if (process.env.NODE_ENV === 'development') {
return merge({}, config, require('./dev'))
}
return merge({}, config, require('./prod'))
}

异步编程

Taro 支持使用 async functions 来让开发者获得不错的异步编程体验,开启 async functions 支持需要安装包 @tarojs/async-await

1
2
3
4
$ yarn add @tarojs/async-await

# 或者使用 npm
$ npm install --save @tarojs/async-await

随后在项目入口文件 app.js 中直接 import ,就可以开始使用 async functions 功能了

1
2
// src/app.js
import '@tarojs/async-await'

参考

Powered by Hexo and Hexo-theme-hiker

Copyright © 2017 - 2023 Keep It Simple And Stupid All Rights Reserved.

访客数 : | 访问量 :