JS构建多端应用
JS构建多端应用
一,需求与介绍
1.1,介绍
1,Taro 是一套遵循 React语法规范的 多端开发 解决方案。现如今市面上端的形态多种多样,Web、React-Native、微信小程序等各种端大行其道,当业务要求同时在不同的端都要求有所表现的时候,针对不同的端去编写多套代码的成本显然非常高,这时候只编写一套代码就能够适配到多端的能力就显得极为需要。
使用 Taro,我们可以只书写一套代码,再通过 Taro 的编译工具,将源代码分别编译出可以在不同端(微信/百度/支付宝/字节跳动小程序、H5、React-Native 等)运行的代码。
2,Taro UI
是一款基于 Taro 框架开发的多端 UI 组件库
1.2,需求
一套代码,多端使用,减少开发成本
二,搭建项目
第一步:全局安装Taro 开发工具 @tarojs/cli
npm/cnpm install -g @tarojs/cli
第二步:创建项目
taro init YingQi
在创建完项目之后,Taro 会默认开始安装项目所需要的依赖,安装使用的工具按照 yarn>cnpm>npm 顺序进行检测。如果安装失败,可以使用如下命令安装
npm/cnpm install
第三步:运行项目
以运行H5为例,输入如下命令
如果看到如下界面,表示运行成功
1.H5
H5预览项目
# npm script
$ npm run dev:h5
# 仅限全局安装
$ taro build --type h5 --watch
# npx 用户也可以使用
$ npx taro build --type h5 --watch
H5打包项目
# npm script
$ npm run build:h5
# 仅限全局安装
$ taro build --type h5
# npx 用户也可以使用
$ npx taro build --type h5
2.微信小程序
微信小程序预览项目
# npm script
$ npm run dev:weapp
# 仅限全局安装
$ taro build --type weapp --watch
# npx 用户也可以使用
$ npx taro build --type weapp --watch
微信小程序打包项目
# npm script
$ npm run build:weapp
# 仅限全局安装
$ taro build --type weapp
# npx 用户也可以使用
$ npx taro build --type weapp
注意:去掉 --watch 将不会监听文件修改,并会对代码进行压缩打包
其他端的预览/打包项目与H5的类似,只需把H5替换为其他的即可,如下:
- 百度只能小程序:swan
- 支付宝小程序:alipay
- React-Native:rn
- 头条/字节跳动小程序:tt
三,配置项目架构
3.1,配置dva
第一步:安装所需的依赖
npm/cnpm install --save dva-loading dva-core redux-logger
第二步:配置dva入口
import Taro from '@tarojs/taro';
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 (Taro.getEnv() === Taro.ENV_TYPE.ALIPAY) {
global = {};
} //注册models
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;
},
};
第三步:配置models文件-home
import {STATUSSUCCESS} from '../utils/const';
import {
Home as namespace,
} from '../utils/namespace';
import {
getSingleDataById,
} from '../services/home'; export default {
namespace: namespace,//'home',
state: {
singleId:'',
tableName:'',
},
effects: {
*getSingleData(_, { call, put,select }) {
const { singleId, tableName } = yield select(state => state[namespace]);
console.log('singleId===',singleId)
const { status, data } = yield call(getSingleDataById, {
singleId,
tableName,
});
if (status ==STATUSSUCCESS) {
yield put({
type: 'save',
payload: {
banner: data.banner,
brands: data.brands,
},
});
}
},
},
reducers: {
save(state, { payload }) {
return { ...state, ...payload };
},
},
};
第四步:配置models的统一入口
import home from './home'; export default [ home];
第五步:引入到项目入口文件
import dva from './entries';
import models from './models';
第六步:在项目入口文件配置
... import { Provider } from '@tarojs/redux'; ... const dvaApp = dva.createApp({
initialState: {},
models: models,
});
const store = dvaApp.getStore(); ... render() {
return (
<Provider store={store}>
...
</Provider>
);
} ...
3.2,配置服务请求
第一步:配置请求方式与返回状态
export const GET = 'GET';
export const POST = 'POST';
export const PUT = 'PUT';
export const PATCH = 'PATCH';
export const DELETE = 'DELETE';
export const UPDATE = 'UPDATE'; export const STATUSSUCCESS = 1;//成功返回状态
第二步:配置请求基础地址与日志是否打印
import Taro from '@tarojs/taro';
// 请求连接前缀
export const baseUrl = Taro.getEnv() === Taro.ENV_TYPE.WEB?'':'http://localhost:8880';//web端使用代理服务,小程序端使用服务前缀 // 开发环境输出日志信息
export const noConsole = (process.env.NODE_ENV === 'development');
第三步:封装request
import Taro from '@tarojs/taro';
import {STATUSSUCCESS} from './const';
import { baseUrl, noConsole } from '../config'; function checkHttpStatus(response) { if (!!noConsole) {
console.log('response===',response)
}
if (response.statusCode >= 200 && response.statusCode < 300) {
return response.data;
}
const error = new Error(response.statusText);
error.response = response;
error.code = response.status;
throw error;
} function getResult(json) {
// const {dispatch} = store;
if (json.status ==STATUSSUCCESS) {
return json;
}
else {
const error = new Error(json.message || json.msg || '数据加载错误!');
error.code = json.code;
error.data = json;
throw error;
}
} export default (url = '', options = {},) => {
let data;
let contentType;
data = options.data;
delete options.data;
contentType = options.contentType;
delete options.contentType;
const opts = {
url: baseUrl + url,
method: 'POST',
...options
};
opts.header = {
...opts.header,
}; // 请求连接前缀
if (opts.method === 'GET') {
url = url.split('?');
url = url[0] + '?' + QueryString.stringify(url[1] ? {...QueryString.parse(url[1]), ...data} : data);
opts.headers['Content-type'] = contentType ? contentType : 'application/x-www-form-urlencoded'; // } else {
opts.header['Content-Type'] = contentType ? contentType : 'application/x-www-form-urlencoded'; //
opts.data = contentType === 'application/json' ? JSON.stringify(data) : serialize(data);
}
if (!!noConsole) {
console.log(
`${new Date().toLocaleString()}【 request ${url} 】DATA=${JSON.stringify(
data
)}`
);
}
return Taro.request(opts)
.then(checkHttpStatus)
.then(getResult)
.catch(err => ({err}));
};
第四步:请求服务
import request from '../utils/request';
import {PUT, POST} from '../utils/const'; /*
***获取单个登录数据***
*/
export async function getSingleDataById(data) {
return request('/api/v1/yingqi/user/getSingleDataById', {data, method: PUT, contentType: 'application/json'});
}
3.3,配置UI组件
第一步:安装UI组件taro-ui
npm/cnpm install taro-ui --save
第二步:配置需要额外编译的源码模块
由于引用 `node_modules` 的模块,默认不会编译,所以需要额外给 H5 配置 `esnextModules`,在 taro 项目的 `config/index.js` 中新增如下配置项:
h5: {
esnextModules: ['taro-ui']
}
第三步:使用taro-ui
// page.js
import { AtButton } from 'taro-ui'
// 除了引入所需的组件,还需要手动引入组件样式
// app.js
import 'taro-ui/dist/style/index.scss' // 全局引入一次即可
<AtButton
onClick={this.handleChange.bind(this)}>
底部关闭幕帘
</AtButton>
3.4,配置iconfont图标
第一步:在iconfont上创建项目
第二步:上传图标并生成代码
第三步:在项目中配置
@font-face {
font-family: 'iconfont'; /* project id 1076290 */
src: url('http://at.alicdn.com/t/font_1076290_m2xyh7ml7qi.eot');
src: url('http://at.alicdn.com/t/font_1076290_m2xyh7ml7qi.eot?#iefix') format('embedded-opentype'),
url('http://at.alicdn.com/t/font_1076290_m2xyh7ml7qi.woff2') format('woff2'),
url('http://at.alicdn.com/t/font_1076290_m2xyh7ml7qi.woff') format('woff'),
url('http://at.alicdn.com/t/font_1076290_m2xyh7ml7qi.ttf') format('truetype'),
url('http://at.alicdn.com/t/font_1076290_m2xyh7ml7qi.svg#iconfont') format('svg');
} .iconfont {
font-family: 'iconfont' !important;
font-size: 32px;
font-style: normal;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
} .icon-more:before {
content: '\e605';
}
第四步:使用
<View className="iconfont icon-more arrow" />
效果如下:
四,常见问题
1,问题:使用inconfont图标时,web端没有显示图标
解决办法:在每一行//at.alicdn.com/t/font_1076290_m2xyh7ml7qi.eot前加“https:”
2,问题:Taro发起请求参数无法识别content-type类型
原因:由于常用的axios/fetch请求参数的头部是headers,而taro的是header,如果继续使用headers会引发content-type
设置失效,变成默认的类型。
解决办法:headers->header
opts.header = {
...opts.header,
};
最新文章
- windows下React-native 环境搭建
- 一道有意思的笔试题引发的对于new操作符的思考
- js for 循环中的 变量问题。
- 初学Node(五)文件I/O
- center
- Leetcode008. String to Integer (atoi)
- Python基础-作用域和命名空间(Scope and Namespace)
- 【Linux/Ubuntu学习1】Linux /etc 目录详解
- centos(linux) 下如何查看端口占用情况及杀死进程
- return的用法
- Building bridges_hdu_4584(排序).java
- 一些Xcode 5的使用提示和技巧
- reids数据类型
- 打包zip下载
- 广州.NET微软技术俱乐部与其他技术群的区别
- Javascript高级编程学习笔记(16)—— 引用类型(5) Function类型
- Integer判断大于 == 127时的坑
- 录毛线脚本,直接抓包手写最简洁的LoadRunner性能测试脚本
- SelectDataTable
- [笔记] Python 图片转字符画
热门文章
- scrapy基础知识之 CrawlSpiders爬取lagou招聘保存在mysql(分布式):
- Windows下通过VNC远程访问Linux服务器,并实现可视化
- Bean property 'transactionManagerBeanName' is not writable or has an invalid set
- kuangbin专题专题四 Frogger POJ - 2253
- 20131214-EditPlus快捷键-第二十一天
- java学习笔记(基础篇)--java关键字与数据类型
- 【题解】埃及分数-C++
- 【朝花夕拾】Android自定义View篇之(十一)View的滑动,弹性滑动与自定义PagerView
- 微信小程序 textarea 层级过高的解决方式
- html css 布局小细节