preface
Taro is a multi-end development solution that follows the React syntax specification. Now at the top of the market form is varied, the Web, the React – Native, WeChat small programs and other side, when the business requirements in different side are required to show at the same time, more than to write code for different end cost is very high, obviously at that time only a set of code can be adapted to varying ability is very need.
Using Taro, we can only write a set of code, and then compile the source code separately into the code that can be run in different ends (wechat small program, H5, React-native, etc.) through Taro’s compilation tool.
Based on Taro, this project built a demonstration of a fashion wardrobe project, involving the complete business logic and functional points of an e-commerce platform. If this project can be mastered, it is believed that other React projects of most companies will be no problem.
Results demonstrate
Check out the demo here (please use Chrome phone mode to preview)
H5 version && Wechat small program version
Technology stack
React + Taro + Dva
Project running
git clone [email protected]:EasyTuan/taro-msparis.git
# Domestic image acceleration node :[email protected]:easytuan/taro-msparis.git
cd taro-msparis
npm install
Development always listen to compile small programs
npm run dev:weapp
# Monitor H5 compilation when developing
npm run dev:h5
# Pages template generated quicklyNPM run tep file nameCopy the code
Project description
Git branch
Init: The overall structure of the framework and does not involve any business logic
Master: A stable release of the project
Feature: Project development branch
The target function
- [x] Beauty List — done
- [X] Beauty detail — complete
- [x] Login, registration — Done
- [x] Personal center — complete
- [x] Coupon — done
- [x] Pocket (shopping cart) — Done
Business introduction
The directory structure
Temp // H5 Compilation result directory ├──.rn_temp // RN Compilation result directory ├── config // Taro compilation result directory ├─ config // Taro configuration directory │ ├── dev. Js // Configuration during development │ ├── │ ├─ prod.js // ├─ prod.js // ├─ screenshots │ ├─ site // H5 Static file (package file) │ ├─ SRC // Source directory │ ├─ Components // Components │ ├─ config // Project development configuration │ ├─ images // Image file │ ├─ image // ├ ─ ─ models / / redux models │ ├ ─ ─ pages / / page file directory │ │ └ ─ ─ home │ │ ├ ─ ─ index. The js / / page logic │ │ ├ ─ ─ index. The SCSS / / page style │ │ │ ├── utils │ ├─ app.js │ ├─ class.pdf │ ├── utils │ ├─ app.js │ ├─ class.pdf │ ├─ class.pdf │ ├─ class.pdf │ ├─ class.pdf │ ├─ class.pdf │ ├─ class.pdf ├─ index.html ├── package.json ├─ template-.js // pagesCopy the code
Partial screenshots show
Home && product details
Pocket && mine
Log on to && Coupons
Installation and use of TARO
Install Taro development tool @tarojs/ CLI
Use NPM or YARN to install the yarn globally, or use NPX directly
$ npm install -g @tarojs/cli
$ yarn global add @tarojs/cli
Copy the code
Create a template project using the command
$ taro init myApp
Copy the code
Enter the project directory to start development, you can choose small program preview mode, or H5 preview mode, if using wechat small program preview mode, you need to download and open wechat developer tools, select preview project root directory.
Wechat small program compilation preview mode
# # NPM script $NPM run dev: weapp global installation only $taro build - type weapp - watch # NPX users can also use $NPX taro build - type weapp --watchCopy the code
H5 compile preview mode
$NPM script $NPM run dev:h5 # Global install only $taro build --type h5 --watch # NPX Users can also use $NPX taro build --type h5 --watchCopy the code
RN compilation preview mode
# NPM script $NPM run dev:rn # Global install only $taro build --type rn --watch # NPX Users can also use $NPX taro build --type rn --watchCopy the code
Of course, having a skeleton at this point is not enough for production development, so we introduce DVA
$ npm i dva-core dva-loading --save
Copy the code
New 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 log // 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; }}Copy the code
And import in the entry file
import dva from './utils/dva'
const dvaApp = dva.createApp({
initialState: {},
models: models,
});
const store = dvaApp.getStore();
Copy the code
Dva integration is complete, let’s encapsulate request network 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}] [interface response:] ',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(' network request Error, statusCode ${statusCode} '); }})}Copy the code
Well, it is time to prepare the development of pages. I like the directory structure of UMI
├─ class.js // ├─ class.js // ├─ class.js // ├─ class.jsCopy the code
Do you want to generate 4 files per page? Could you use a script to generate it for us automatically? So let’s write one
/** * pages NPM run tep 'filename' */ const fs = require('fs'); const dirName = process.argv[2]; if (! DirName) {console.log(' folder name cannot be empty! '); Console. log(' example: NPM run tep test'); process.exit(0); } // Page template 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> ) } } `; // const scssTep = '@import ".. /.. /styles/mixin"; .${dirName}-page { @include wh(100%, 100%); } `; 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 }; ,}}}; `; Const serviceTep = 'import Request from '.. /.. /utils/request'; Export const demo = (data) => {return Request({url: 'path ', 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(' template ${dirName} has been created, please manually add 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);Copy the code
Now it’s time for fun development…
The directory structure
Temp // H5 Compilation result directory ├──.rn_temp // RN Compilation result directory ├── config // Taro compilation result directory ├─ config // Taro configuration directory │ ├── dev. Js // Configuration during development │ ├── │ ├─ prod.js // ├─ prod.js // ├─ screenshots │ ├── ─ components │ ├── config │ ├── images // Files │ ├─ models // Redux models │ ├ ─ ─ pages / / page file directory │ │ └ ─ ─ home │ │ ├ ─ ─ index. The js / / page logic │ │ ├ ─ ─ index. The SCSS / / page style │ │ ├ ─ ─ model. The js / / page models │ │ ├── class.pdf │ ├── class.pdf │ ├─ class.pdf │ ├─ class.pdf │ ├─ class.pdf │ ├─ class.pdf │ ├─ class.pdf │ ├─ class.pdf │ ├─ class.pdf │ ├─ class.pdf │ ├─ class.pdf │ ├─ class.pdf │ ├─ class.pdf │ ├─ class.pdf │ ├─ class.pdf │ ├─ class.pdf ├ ─ template-.js // pagesCopy the code
Write in the last
The complete code address of the project
The document
Taro Development Document
Nervjs. Making. IO/taro/docs/R…
Dva development document address
dvajs.com/
Small program development documentation
Mp.weixin.qq.com/debug/wxado…