Recently, I have been doing the development of small program projects, which is directly wepy with a similar style to VUE. On the whole, it is stable, and the development efficiency is higher than the original; Many people also know that MPVUE is built with VUE, but always feel that losing the routing VUE is like losing the soul; The Taro framework is a multipurpose development solution that follows the React syntax.
Taro development document: nervjs. Making. IO/taro/docs/R…
Here I will share with you my initial learning process and build a general framework. I have always remembered a sentence of my current boss Vega:
“During the learning process, even if I could copy the code, I would type it again to deepen the impression.”
So if you are interested, you can do it step by step:
One: Install the Taro development tool@tarojs/cli
npm install -g @tarojs/cli
Copy the code
Two: create template projects using commands
taro init taro-react-mini-program
Copy the code
You can choose whether to use TS, SASS, or less depending on your needs, and once the dependencies are installed, the project is built.
Three: project directory structure
├ ─ ─ dist directory compiled results ├ ─ ─ the config configuration directory | ├ ─ ─ dev. The development of a js configuration | ├ ─ ─ index. The default configuration | js └ ─ ─ the prod. Js packaging configuration ├ ─ ─ the SRC source directory | ├ ─ ─ pages Page file directory | | ├ ─ ─ index index page directory | | | ├ ─ ─ index. The js index page logic | | | └ ─ ─ index. The CSS style index page | ├ ─ ─ app. The CSS style of total project general | └ ─ ─ ├ ── package.json app.js project entry fileCopy the code
The use of the framework and matters needing attention are introduced in the document. I mainly write some project configurations and pits I have stepped on.
Some dependencies need to be installed first
npm install tslint stylelint tslint-config-prettier -D
Copy the code
Code specification.prettierrc
{
"stylelintIntegration": true."tslintIntegration": true."tabWidth": 2."singleQuote": true."semi": false
}
Copy the code
.prettierignore
/**/libs/**
dist/
lib/
Copy the code
Style specification:.stylelintrc.js
module.exports = {
ignoreFiles: ['**/*.md'.'**/*.ts'.'**/*.tsx'.'**/*.js']}Copy the code
.stylelintignore
**/dist
Copy the code
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], // ending with a semicolon //"trailing-comma": [false], // Must end with a comma //"requireForBlockBody": true,}}Copy the code
Git commit = commit = commit = commit = commit = commit
Juejin. Cn/post / 684490…
Add a.gitignore file to your configuration, and that’s it. We have roughly all the configuration files we need. Look at the results:
When there is non-standard code submitted
Commit after all the issues are resolved, of course tsLint and other configurations are custom and can be configured yourself. Feel troublesome can according to their own “taste” configuration project
Then we can have fun developing our programs, running NPM Run Dev: Pervasive, and restarting our apps
Many people reported that there would always be mistakes in using native taron. request or using third-party axios to make asynchronous requests. I didn’t test it personally, but I encapsulated the method with promise and created utils folder under the root directory SRC folder. And check whether the session is expired, bind the user scenario to write a general example, the interface is fictitious:
├ ─ ─ utils | ├ ─ ─ API. Ts request interface Settings | ├ ─ ─ HTTP. Public ts HTTP request file | └ ─ ─ index. The tsCopy the code
The http.ts code is as follows:
import Taro from '@tarojs/taro'
import md5 from 'blueimp-md5'
type HttpMethods = 'GET' | 'POST' | 'PUT' | 'DELETE'// Whether the backend supports json format 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('Network request error')}})}}Copy the code
api.ts
import Http from './http'Const HTTP = new HTTP () // automatic login const URL ='xxxxx'
export const login = (data: object) => http.post(url, data)
Copy the code
Index.ts (custom common processing interface file)
import Taro from '@tarojs/taro'
import { login } from './api'// Get wechat login credentialsexport const wxLogin = async () => {
try {
const res = await Taro.login()
return res.code
} catch (error) {
console.log('wechat get temporary with failure')}}export const userLogin = async () => {
try {
await Taro.checkSession()
if(! Taro.getStorageSync('token')) {
throw new Error('No cached token locally') } } catch (error) { const code = await wxLogin() const loginRes: any = await login({ code // ... (Other parameters)}) console.log('User data', loginRes)
}
}
Copy the code
Finally, reference it in pages/index/index.tsx
import { userLogin } from '.. /.. /utils/index'. asynccomponentDidMount() {
await userLogin()
}
Copy the code
React’s calligraphy style is quite comfortable. If you are used to vue writing, you may feel uncomfortable at first. If you are interested, try it out.
One: the introduction of pictures in the way of modules
If static resources such as images cannot be found, the image must be declared as a module:
Under global.d.ts in the Types directory:
Declare the module ‘*. {PNG’
const img: any
export default img
}
Two: dynamic add style
<View style={{backgroundImage: `url(${bgImg})`}}></View>
Copy the code
Three: Dynamically add classes
1.<View className={data.length>0? 'the class - yes' :' the class - no'}> 2.
0? Class - 'yes' :' ` class - no}} > < / View >
Copy the code
Four: the orientation of this problem
In the Taro pages and component classes, this refers to an instance of an Taro page or component. If we want to reference a native component, we need to use this if we refer to:
Taro.createCanvasContext(canvasId, this.$scope)
wx.createLivePlayerContext(liveId, this.$scope)
Error: wx. CreateLivePlayerContext (liveId, this introduction is of no effect, this is not to wx. CreateLivePlayerContext.
(The current version does not have livePlayer callback methods, so use native WX)
Five: global style issues
Global raw app.scSS only affects page-level files, components don’t get global styles,
It is possible to import global style files inside components, but here it is possible to import globals from multiple components and generate multiple global style files
The corresponding code I uploaded to my Github:
Github.com/YDMua/taro-…