最近一直在作小程序項目的開發,上手直接就是wepy, 風格跟vue差很少,總體上,還算穩定,開發起來比原生的效率要高一點;不少人也知道,mpvue就是用vue搭建的,但始終以爲,失去了路由的vue,就像失去了靈魂;雖然接下來要給你們安利的框架,也貌似失去了該靈魂- taro框架(Taro 是一套遵循 React 語法規範的 多端開發 解決方案。)css
taro開發文檔: nervjs.github.io/taro/docs/R…html
在這裏我將我初步入坑的學習過程,以及構建了大體框架與你們分享下,一直深記我如今的大佬vega的一句話:vue
「在學習過程當中,即便能夠複製的代碼,我都會再本身敲一遍加深印象」react
因此感興趣的小夥伴,也能夠跟着一步一步作:ios
@tarojs/cli
npm install -g @tarojs/cli
複製代碼
taro init taro-react-mini-program
複製代碼
能夠根據本身的須要,選擇是否使用ts, sass或者less, 接着等安裝好依賴,項目就構建完成;git
├── dist 編譯結果目錄
├── config 配置目錄
| ├── dev.js 開發時配置
| ├── index.js 默認配置
| └── prod.js 打包時配置
├── src 源碼目錄
| ├── pages 頁面文件目錄
| | ├── index index頁面目錄
| | | ├── index.js index頁面邏輯
| | | └── index.css index頁面樣式
| ├── app.css 項目總通用樣式
| └── app.js 項目入口文件
└── package.json
複製代碼
框架的使用和注意事項,文檔中有介紹,我這邊主要寫一些項目配置和踩過的坑;github
這裏須要先安裝一些依賴npm
npm install tslint stylelint tslint-config-prettier -D
複製代碼
代碼規範 .prettierrcjson
{
"stylelintIntegration": true,
"tslintIntegration": true,
"tabWidth": 2,
"singleQuote": true,
"semi": false
}
複製代碼
.prettierignorecanvas
/**/libs/**
dist/
lib/
複製代碼
樣式規範: .stylelintrc.js
module.exports = {
ignoreFiles: ['**/*.md', '**/*.ts', '**/*.tsx', '**/*.js']
}
複製代碼
.stylelintignore
**/dist
複製代碼
tslint.json
{
"extends": ["tslint:recommended", "tslint-config-prettier"],
"rules": {
"ordered-imports": false,
"object-literal-sort-keys": false,
"member-access": false,
"member-ordering": false,
"no-empty-interface": false,
"no-console": [true, "warning"],
"interface-name": [true, "never-prefix"],
"no-empty": false,
"quotemark": [true, "single"]
// "semicolon": [false], // 結尾比較分號
// "trailing-comma": [false], // 結尾必須逗號
// "requireForBlockBody": true,
}
}
複製代碼
接着配置git的提交commit提交驗證,須要安裝對應的依賴包,能夠從個人另一篇文章看:
再加上本身配置一個.gitignore文件,就這樣,咱們將大體須要的配置文件都配置好了;看看效果:
當有不規範的代碼提交的時候
把全部問題都解決以後提交,固然tslint以及其餘的一些配置都是自定義的,能夠本身配置。以爲麻煩的能夠根據本身的「口味」配置項目
而後咱們就能夠愉快的開發咱們的項目,運行npm run dev:weapp,打開咱們的小程序
不少人反饋用原生的 Taro.request或者用第三方axios等等作異步請求總會有錯,我沒親測,可是本身用promise封裝了方法, 在根目錄src文件夾下建立utils文件夾, 在這裏我簡單的模擬微信受權登陸,以及檢測session是否過時,綁定用戶的場景寫一個大概例子,接口爲虛構:
├── utils
| ├── api.ts 請求接口設置
| ├── http.ts http公共請求文件
| └── index.ts
複製代碼
http.ts代碼以下:
import Taro from '@tarojs/taro'
import md5 from 'blueimp-md5'
type HttpMethods = 'GET' | 'POST' | 'PUT' | 'DELETE'
// 後端是否支持json格式
const contentType = 'application/x-www-form-urlencoded'
// const contentType = 'application/json'
export default class Http {
noNeedToken = ['mockFakeApi']
get(url: string, data: object) {
return this.commonHttp('GET', url, data)
}
post(url: string, data: object) {
return this.commonHttp('POST', url, data)
}
async commonHttp(method: HttpMethods, url: string, data: object) {
return new Promise<any>(async (resolve, reject) => {
Taro.showNavigationBarLoading()
try {
const res = await Taro.request({
url,
method,
data,
header: {
'content-type': contentType
}
})
Taro.hideNavigationBarLoading()
switch (res.statusCode) {
case 200:
return resolve(res.data.response)
default:
console.log(res.data.message)
reject(new Error(res.data.msg))
}
} catch (error) {
Taro.hideNavigationBarLoading()
reject(new Error('網絡請求出錯'))
}
})
}
}
複製代碼
api.ts
import Http from './http'
const http = new Http()
// 自動登陸
const url = 'xxxxx'
export const login = (data: object) => http.post(url, data)
複製代碼
index.ts (自定義公共處理接口文件)
import Taro from '@tarojs/taro'
import { login } from './api'
// 獲取微信登陸憑證
export const wxLogin = async () => {
try {
const res = await Taro.login()
return res.code
} catch (error) {
console.log('微信獲取臨時憑着失敗')
}
}
export const userLogin = async () => {
try {
await Taro.checkSession()
if (!Taro.getStorageSync('token')) {
throw new Error('本地沒有緩存token')
}
} catch (error) {
const code = await wxLogin()
const loginRes: any = await login({
code
// ...(其餘參數)
})
console.log('用戶數據', loginRes)
}
}
複製代碼
最後在pages/index/index.tsx中引用就行了
import { userLogin } from '../../utils/index'
....
async componentDidMount() {
await userLogin()
}
複製代碼
整個框架的使用大體就是這樣了,react的書法風格仍是挺舒服的,若是習慣了vue的寫法可能剛開始會不習慣,有興趣的能夠嘗試嘗試,下面再簡單的把一些小技巧給補上:
使用ts搭建的項目,引入靜態資源,好比圖片,會提示找不到模塊,這時候就必須將圖片聲明爲一個模塊:
在types目錄的global.d.ts文件下:
declare module ‘*.png’ {
const img: any
export default img
}
<View style={{backgroundImage: `url(${bgImg})`}}></View>
複製代碼
1.<View className={data.length>0?’class-yes’: ’class-no'}></View> 2.<View className={`common ${data.length>0?’class-yes’: ’class-no}`}></View> 複製代碼
1)在 Taro 的頁面和組件類中,this
指向的是 Taro 頁面或組件的實例,若是咱們要引用原生組件,須要使用到this的時候,若是以下引用:
Taro.createCanvasContext(canvasId, this.$scope)
wx.createLivePlayerContext(liveId, this.$scope)
錯誤:wx.createLivePlayerContext(liveId, this)這樣引入是沒有效果的,this並非指向 wx.createLivePlayerContext.
(當前版本沒有liveplayer的回調方法,因此直接用原生wx)
全局原始app.scss 只會影響到頁面級別的文件,組件的獲取不到全局的樣式,
能夠在組件內部import 全局樣式文件,可是這裏就有可能,多個組件都引入全局,生成多份全局樣式文件
相對應的代碼我上傳到了個人github: