taro的安装及使用

安装 Taro 开发工具 @tarojs/cli

使用 npm 或者 yarn 全局安装,或者直接使用npx

$ npm install -g @tarojs/cli
$ yarn global add @tarojs/cli

使用命令创建模板项目

$ taro init myApp

进入项目目录开始开发,可以选择小程序预览模式,或者 h5 预览模式,若使用微信小程序预览模式,则需要自行下载并打开微信开发者工具,选择预览项目根目录。

微信小程序编译预览模式

# npm script
$ npm run dev:weapp
# 仅限全局安装
$ taro build --type weapp --watch
# npx 用户也可以使用
$ npx taro build --type weapp --watch

H5 编译预览模式

# npm script
$ npm run dev:h5
# 仅限全局安装
$ taro build --type h5 --watch
# npx 用户也可以使用
$ npx taro build --type h5 --watch

RN 编译预览模式

# npm script
$ npm run dev:rn
# 仅限全局安装
$ taro build --type rn --watch
# npx 用户也可以使用
$ npx taro build --type rn --watch

当然到这一步有个大概的骨架,作为生产开发是不够的,这时候我们引入dva

$ npm i dva-core dva-loading --save

新建dva.js

import { create } from 'dva-core';
import { createLogger } from 'redux-logger';
import createLoading from 'dva-loading'; let app;
let store;
let dispatch; function createApp(opt) {
// redux日志
// opt.onAction = [createLogger()];
app = create(opt);
app.use(createLoading({})); if (!global.registered) opt.models.forEach(model => app.model(model));
global.registered = true;
app.start(); store = app._store;
app.getStore = () => store; dispatch = store.dispatch; app.dispatch = dispatch;
return app;
} export default {
createApp,
getDispatch() {
return app.dispatch;
}
}

并在入口文件导入

import dva from './utils/dva'
const dvaApp = dva.createApp({
initialState: {},
models: models,
});
const store = dvaApp.getStore();

dva集成好了,下面我们来封装下request网络请求吧

import Taro from '@tarojs/taro';
import { baseUrl, noConsole } from '../config'; export default (options = { method: 'GET', data: {} }) => {
if (!noConsole) {
console.log(`${new Date().toLocaleString()}【 M=${options.url} 】P=${JSON.stringify(options.data)}`);
}
return Taro.request({
url: baseUrl + options.url,
data: options.data,
headers: {
'Content-Type': 'application/json',
},
method: options.method.toUpperCase(),
}).then((res) => {
const { statusCode, data } = res;
if (statusCode >= 200 && statusCode < 300) {
if (!noConsole) {
console.log(`${new Date().toLocaleString()}【 M=${options.url} 】【接口响应:】`,res.data);
}
if (data.status !== 'ok') {
Taro.showToast({
title: `${res.data.error.message}~` || res.data.error.code,
icon: 'none',
mask: true,
});
}
return data;
} else {
throw new Error(`网络请求错误,状态码${statusCode}`);
}
})
}

好了,是应该准备pages页面的开发了,本人比较喜欢umi的目录结构

  pages                  // 页面文件目录
└── home
├── index.js // 页面逻辑
├── index.scss // 页面样式
├── model.js // 页面models
└── service.css // 页面api

一个page要生成4个文件?能否用脚本帮我们自动生成呢?那来写一个吧

 /**
* pages模版快速生成脚本,执行命令 npm run tep `文件名`
*/ const fs = require('fs'); const dirName = process.argv[2]; if (!dirName) {
console.log('文件夹名称不能为空!');
console.log('示例:npm run tep test');
process.exit(0);
} // 页面模版
const indexTep = `import Taro, { Component } from '@tarojs/taro';
import { View } from '@tarojs/components';
import { connect } from '@tarojs/redux';
import './index.scss'; @connect(({${dirName}}) => ({
...${dirName},
}))
export default class ${titleCase(dirName)} extends Component {
config = {
navigationBarTitleText: '${dirName}',
}; componentDidMount = () => { }; render() {
return (
<View className="${dirName}-page">
${dirName}
</View>
)
}
}
`; // scss文件模版
const scssTep = `@import "../../styles/mixin"; .${dirName}-page {
@include wh(100%, 100%);
}
`; // model文件模版
const modelTep = `import * as ${dirName}Api from './service'; export default {
namespace: '${dirName}',
state: { }, effects: {
* effectsDemo(_, { call, put }) {
const { status, data } = yield call(${dirName}Api.demo, {});
if (status === 'ok') {
yield put({ type: 'save',
payload: {
topData: data,
} });
}
},
}, reducers: {
save(state, { payload }) {
return { ...state, ...payload };
},
}, };
`; // service页面模版
const serviceTep = `import Request from '../../utils/request'; export const demo = (data) => {
return Request({
url: '路径',
method: 'POST',
data,
});
};
`; fs.mkdirSync(`./src/pages/${dirName}`); // mkdir $1
process.chdir(`./src/pages/${dirName}`); // cd $1 fs.writeFileSync('index.js', indexTep);
fs.writeFileSync('index.scss', scssTep);
fs.writeFileSync('model.js', modelTep);
fs.writeFileSync('service.js', serviceTep); console.log(`模版${dirName}已创建,请手动增加models`); function titleCase(str) {
const array = str.toLowerCase().split(' ');
for (let i = 0; i < array.length; i++) {
array[i] = array[i][0].toUpperCase() + array[i].substring(1, array[i].length);
}
const string = array.join(' ');
return string;
} process.exit(0);

现在是时候进行愉快的开发了。。。

目录结构

├── .temp                  // H5编译结果目录
├── .rn_temp // RN编译结果目录
├── dist // 小程序编译结果目录
├── config // Taro配置目录
│ ├── dev.js // 开发时配置
│ ├── index.js // 默认配置
│ └── prod.js // 打包时配置
├── screenshots // 项目截图,和项目开发无关
├── src // 源码目录
│ ├── components // 组件
│ ├── config // 项目开发配置
│ ├── images // 图片文件
│ ├── models // redux models
│ ├── pages // 页面文件目录
│ │ └── home
│ │ ├── index.js // 页面逻辑
│ │ ├── index.scss // 页面样式
│ │ ├── model.js // 页面models
│ │ └── service.js // 页面api
│ ├── styles // 样式文件
│ ├── utils // 常用工具类
│ ├── app.js // 入口文件
│ └── index.html
├── package.json
└── template.js // pages模版快速生成脚本,执行命令 npm run tep `文件名`

.

taro + taro-ui + dva的更多相关文章

  1. [Taro] taro中定义以及使用全局变量

    taro中定义以及使用全局变量 错误的姿势 // app.tsx文件中 class App extends Component { componentDidMount() { this.user = ...

  2. [Taro] Taro 环境安装 (一)

    Taro  环境安装 Taro是一个前端小程序框架,通过这个框架写一套代码,再通过 Taro 的编译工具,就可以将源代码分别编译出可以在不同端(微信/百度/支付宝/字节跳动小程序.H5.React-N ...

  3. [Taro] taro 缓存

    taro 缓存 Taro.clearStorageSync() 清除全部缓存 Taro.setStorage(key,value)设置缓存 Taro.getStorage(key)获取缓存 Taro. ...

  4. taro taro 多端同步调试

    taro 多端同步调试 debug https://nervjs.github.io/taro/docs/envs-debug.html

  5. Taro UI开发小程序实现左滑喜欢右滑不喜欢效果

    前言:年后入职了一家新公司,与前同事交接完之后,发现公司有一个四端的项目(iOS,Android,H5,小程序),iOS和安卓都实现了左滑右滑的效果,而h5和小程序端没实现,询问得知前同事因网上没找到 ...

  6. 用Taro写一个微信小程序(三)—— 配置dva

    一.关于dva dva 首先是一个基于 redux 和 redux-saga 的数据流方案,然后为了简化开发体验,dva 还额外内置了 react-router 和 fetch,所以也可以理解为一个轻 ...

  7. 小程序第三方框架对比 ( wepy / mpvue / taro )(转)

    文章转自  https://www.cnblogs.com/Smiled/p/9806781.html 众所周知如今市面上端的形态多种多样,手机Web.ReactNative.微信小程序, 支付宝小程 ...

  8. 小程序第三方框架对比 ( wepy / mpvue / taro )

      众所周知如今市面上端的形态多种多样,手机Web.ReactNative.微信小程序, 支付宝小程序, 快应用等,每一端都是巨大的流量入口,当业务要求同时在不同的端都要求有所表现的时候,针对不同的端 ...

  9. taro 学习资料

    taro 学习资料 学习资料 网址 github https://github.com/NervJS/taro taro 官方文档 https://nervjs.github.io/taro/docs ...

  10. taro 更新

    更新 Taro 提供了更新命令来更新 CLI 工具自身和项目中 Taro 相关的依赖 更新 Taro CLI 工具 # taro $ taro update self # npm npm i -g @ ...

随机推荐

  1. HZAU 1205 Sequence Number(双指针)

    题目链接:http://acm.hzau.edu.cn/problem.php?id=1205 [题意]给你一串数,要求你找到两个数a[i],a[j],使得a[i]<=a[j]且j>=i且 ...

  2. Sqli-labs介绍、下载、安装

    SQLI和sqli-labs介绍 SQLI,sql injection,我们称之为sql注入.何为sql,英文:Structured Query Language,叫做结构化查询语言.常见的结构化数据 ...

  3. 苹果Itools

    韩梦飞沙  韩亚飞  313134555@qq.com  yue31313  han_meng_fei_sha

  4. 【HDU 5730】Shell Necklace

    http://acm.hdu.edu.cn/showproblem.php?pid=5730 分治FFT模板. DP:\(f(i)=\sum\limits_{j=0}^{i-1}f(j)\times ...

  5. 【费用流】NOI2008志愿者招募

    1061: [Noi2008]志愿者招募 Time Limit: 20 Sec  Memory Limit: 162 MBSubmit: 5171  Solved: 3089[Submit][Stat ...

  6. BZOJ 1260 [CQOI2007]涂色paint(区间DP)

    [题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=1260 [题目大意] 假设你有一条长度为n的木版,初始时没有涂过任何颜色 每次你可以把一 ...

  7. [BZOJ3576]江南乐

    挺好的题 我们算出每个数的sg值后异或起来即可 对于$n$,我们要求$sg_n$ 朴素的想法是枚举把$n$个石子分成$m$堆,有$m-n\%m$堆大小为$\left\lfloor\frac nm\ri ...

  8. python基础之封装与绑定方法

    封装 1.什么是封装: 封:属性对外隐藏,但对内开放 装:申请一个名称空间,往里装入一系列名字/属性 2.为什么要封装: 封装数据属性:不让外部使用者直接使用数据,需要类内部开辟一个接口,让外部通过接 ...

  9. [AGC025D]Choosing Points

    [AGC025D]Choosing Points 题目大意: 输⼊\(n(n\le300),d_1,d_2\),你要找到\(n^2\)个整点\((x,y)\)满⾜\(0\le x,y<2n\). ...

  10. [bzoj1011](HNOI2008)遥远的行星(近似运算)

    Description 直 线上N颗行星,X=i处有行星i,行星J受到行星I的作用力,当且仅当i<=AJ.此时J受到作用力的大小为 Fi->j=Mi*Mj/(j-i) 其中A为很小的常量, ...