当前位置:网站首页>Introduction to taro
Introduction to taro
2022-06-29 08:08:00 【m0_ forty-nine million four hundred and seventy-one thousand si】
brief introduction
Taro It's an open Span end span frame Solution , Support use React/Vue/Nerv Wait for the framework to develop WeChat / JD.COM / Baidu / Alipay / Bytes to beat / QQ / anonymous letter Applet / H5 / RN And so on .
Nowadays, there are various forms on the market ,Web、React Native、 Wechat applets and other terminals are popular . When business requirements require performance at different ends at the same time , The cost of writing multiple sets of code for different ends is obviously very high , At this time, it is extremely necessary to write only one set of code to adapt to multiple ends .
characteristic
Multiterminal conversion support
Taro 3 Can support conversion to H5、ReactNative And any applet platform .
At present, the platforms officially supporting the conversion are as follows :
- H5
- ReactNative
- Wechat applet
- Jingdong applet
- Baidu applet
- Alipay applet
- Bytedance applet
- QQ Applet
- Pin applet
- Enterprise wechat app
- Alipay IOT Applet
- Flying Book applet
Taro UI
Taro 3 Can only be used in conjunction with [email protected] edition
Installation command :
npm i [email protected]Based on a
TaroMulti end of framework development UI Component library . Taro UI characteristic :
- be based on
TaroDevelopment UI Components - A set of components can be adapted to run at multiple ends (
ReactNativeThe client does not support ) - Offer friendly API, Flexible use of components
Step by step tutorial
at present Taro Only one way of development : install Taro Command line tools (Taro CLI) Development .
Taro CLI Depend on Node.js Environmental Science , So you must install on your machine Node.js Environmental Science . install Node.js There are many ways to improve the environment , If you don't understand at all Node.js You can visit Node.js Official website Download an executable program to install . We recommend installing LTS Version of Node.js( at present LTS The version is v12).
Environmental preparation
at present Taro Only one way of development : install Taro Command line tools (Taro CLI) Development .
Taro CLI Depend on Node.js Environmental Science , So you must install on your machine Node.js Environmental Science . install Node.js There are many ways to improve the environment , If you don't understand at all Node.js You can visit Node.js Official website Download an executable program to install . We recommend installing LTS Version of Node.js( at present LTS The version is v12).
When your machine already exists Node.js Environmental Science , You can enter commands at the terminal npm i -g @tarojs/cli install Taro CLI. After installation , Enter the command at the terminal taro, If something similar appears, the installation is successful :
Taro v3.0.0-beta.6
Usage: taro <command> [options]
Options:
-V, --version output the version number
-h, --help output usage information
Commands:
init [projectName] Init a project with default templete
config <cmd> Taro config
create Create page for project
build Build a project with options
update Update packages of taro
convert Convert weapp to taro
info Diagnostics Taro env info
doctor Diagnose taro project
help [cmd] display help for [cmd]Basic course
Install well Taro CLI And then you can go through taro init Command to create a new project , You can fill in the options according to your project needs , A minimal version of Taro The project will include the following documents
├── babel.config.js # Babel To configure
├── .eslintrc.js # ESLint To configure
├── config # Compile configuration directory
│ ├── dev.js # Development mode configuration
│ ├── index.js # The default configuration
│ └── prod.js # Production mode configuration
├── package.json # Node.js manifest
├── dist # Package directory
├── project.config.json # Applet project configuration
├── src # Source directory
│ ├── app.config.js # Global configuration
│ ├── app.css # overall situation CSS
│ ├── app.js # Entrance assembly
│ ├── index.html # H5 entrance HTML
│ └── pages # Page components
│ └── index
│ ├── index.config.js # Configuration page
│ ├── index.css # page CSS
│ └── index.jsx # Page components , If it is Vue project , This document is index.vue We will explain the function of each file later , But now , Let's focus on src Folder , That is, the source code directory :
Entrance assembly
every last Taro Each project has an entry component and an entry configuration , We can set the global state in the entry component / Global lifecycle , A minimal entry component would look like this :
import React, { Component } from 'react'
import './app.css'
class App extends Component {
render () {
// this.props.children Is the page that will be rendered
return this.props.children
}
}
// Each entry component must export a React Components
export default App Each entry component ( for example app.js) Always accompanied by a global configuration file ( for example app.config.js), We can set the path of the page component in the global configuration file 、 Global window 、 Routing information , The simplest global configuration is as follows :
src/app.config.js
export default {
pages: [
'pages/index/index'
]
}Taro Installation and use of the official website :https://nervjs.github.io/taro/docs/GETTING-STARTED.html
1、 install node
2、 Install the image
You can use the mirror image of Taobao https://npm.taobao.org/ Open the command terminal npm install -g cnpm --registry=https://registry.npm.taobao.org
3、 install Taro development tool @tarojs/cli
npm install -g @tarojs/cli
4、 Use the command to create a template project
taro init myApp
5、 Entry project
cd myApp
6、 Open the project view ( The operation here is H5)
npm run dev:h5
Compile operation
Use Taro Of build Orders can put Taro Code is compiled into different end code , Then check the effect in the corresponding development tool .
Taro Compilation is divided into dev and build Pattern :
- dev Pattern ( increase --watch Parameters ) Will listen for file modification .
- build Pattern ( Get rid of --watch Parameters ) File modification will not be monitored , And will compress and package the code .
- dev The file generated by the schema is large , Set the environment variable
NODE_ENVbyproductionCompression can be turned on , Easy preview , But the compilation speed will decrease .
Wechat applet
Compile command
# yarn
$ yarn dev:weapp
$ yarn build:weapp
# npm script
$ npm run dev:weapp
$ npm run build:weapp
# Global installation only
$ taro build --type weapp --watch
$ taro build --type weapp
# npx Users can also use it
$ npx taro build --type weapp --watch
$ npx taro build --type weapp
# watch Turn on compression at the same time
$ set NODE_ENV=production && taro build --type weapp --watch # Windows
$ NODE_ENV=production taro build --type weapp --watch # Mac
Applet developer tools
Download and open WeChat developer tools , And then choose Project root To preview .
Note the project settings of the developer tool :
- You need to set the shutdown ES6 turn ES5 function , Error may be reported when opening
- You need to set the style auto completion when uploading code is turned off , Error may be reported when opening
- You need to set to turn off code compression uploading , Error may be reported when opening
Directory structure
Project directory structure
├── dist Compile results directory
|
├── config Project compilation configuration directory
| ├── index.js The default configuration
| ├── dev.js Development environment configuration
| └── prod.js Production environment configuration
|
├── src Source directory
| ├── pages Page file directory
| | └── index index Page directory
| | ├── index.js index Page logic
| | ├── index.css index Page style
| | └── index.config.js index Configuration page
| |
| ├── app.js Project entry documents
| ├── app.css Project general style
| └── app.config.js Project entrance configuration
|
├── project.config.json Wechat applet project configuration project.config.json
├── project.tt.json Byte runout applet project configuration project.tt.json
├── project.swan.json Baidu applet project configuration project.swan.json
├── project.qq.json QQ Applet project configuration project.qq.json
|
├── babel.config.js Babel To configure
├── tsconfig.json TypeScript To configure
├── .eslintrc ESLint To configure
|
└── package.jsonCompile configuration
The compilation configuration is stored in the project root directory config Directory , It contains three files :
index.jsIt is a universal configurationdev.jsIt is the configuration during project previewprod.jsIt is the configuration when the project is packaged
For detailed compilation configuration documents, please refer to : Compile configuration details
The default configuration
config/index.js
const config = {
// Project name
projectName: 'Awesome Next',
// Project creation date
date: '2020-6-2',
// Design draft size
designWidth: 750,
// Rules for size conversion of design documents
deviceRatio: {
640: 2.34 / 2,
750: 1,
828: 1.81 / 2
},
// Project source directory
sourceRoot: 'src',
// Project output catalogue
outputRoot: 'dist',
// Taro The plug-in configuration
plugins: [],
// Global variable Settings
defineConstants: {},
// file copy To configure
copy: {
patterns: [
],
options: {
}
},
// frame ,react,nerv,vue, vue3 etc.
framework: 'react',
// Applet side dedicated configuration
mini: {
postcss: {
autoprefixer: {
enable: true
},
// The applet side style refers to the local resource inline configuration
url: {
enable: true,
config: {
limit: 10240
}
},
cssModules: {
enable: false, // The default is false, If you want to use css modules function , Set to true
config: {
namingPattern: 'module', // Conversion mode , The value is global/module
generateScopedName: '[name]__[local]___[hash:base64:5]'
}
}
},
// Customize Webpack To configure
webpackChain (chain, webpack) {}
},
// H5 End specific configuration
h5: {
publicPath: '/',
staticDirectory: 'static',
postcss: {
autoprefixer: {
enable: true
},
cssModules: {
enable: false, // The default is false, If you want to use css modules function , Set to true
config: {
namingPattern: 'module', // Conversion mode , The value is global/module
generateScopedName: '[name]__[local]___[hash:base64:5]'
}
}
},
// Customize Webpack To configure
webpackChain (chain, webpack) {},
devServer: {}
}
};
module.exports = function(merge) {
if (process.env.NODE_ENV === 'development') {
return merge({}, config, require('./dev'));
}
return merge({}, config, require('./prod'));
};Design draft and dimension unit
stay Taro Medium size units are recommended px、 percentage %,Taro All units are converted by default . stay Taro The size of the writing is in accordance with 1:1 To write about the relationship between , That is, the length measured from the design draft 100px, So size writing is 100px, When it turns into a wechat app , Dimensions will be converted to... By default 100rpx, When it turns into H5 Convert the default to rem Is the value of the unit .
If you want part of px Units are not converted to rpx perhaps rem , The easiest way to do it is to px Add a capital letter to the unit , for example Px perhaps PX such , Will be ignored by the conversion plug-in .
Combined with past development experience ,Taro Default to 750px As a conversion dimension standard , If the design is not based on 750px As the standard , You need to configure config/index.js Set in , For example, the size of the design draft is 640px, You need to modify the project configuration config/index.js Medium designWidth Configure to 640:
/config/index.js
const config = {
projectName: 'myProject',
date: '2018-4-18',
designWidth: 640,
....
}
at present Taro Support 750、 640 、 828 Three sizes of design drafts , Their conversion rules are as follows :
const DEVICE_RATIO = {
'640': 2.34 / 2,
'750': 1,
'828': 1.81 / 2
}
It is recommended to use Taro when , Design draft to iPhone 6 750px As the design dimension standard .
If your design is 375 , Not among the above three , Then you need to put designWidth Configure to 375, At the same time DEVICE_RATIO Add conversion rules in as follows :
const DEVICE_RATIO = {
'640': 2.34 / 2,
'750': 1,
'828': 1.81 / 2,
'375': 2 / 1
}
INFO
Taro v3.4.3 Start to support configuration Function form Of designWidth, This allows developers to dynamically set designWidth, Please check the details :config.designWidth
https://taro-docs.jd.com/taro/docs/config-detail#designwidth
API
At compile time ,Taro It will help you to convert the size of the style , But if it's in JS In the middle book, the style in the line is written , Then there is no replacement at compile time , In this case ,Taro Provides API Taro.pxTransform To do the size conversion at runtime .
Taro.pxTransform(10) // Applet :rpx,H5:remTo configure
The default configuration
The default configuration will px Units for conversion , Having capital letters Px or PX Will be ignored .
postcss.pxtransform The default values of the parameters are as follows :
config/index.js
config = {
mini: {
postcss: {
pxtransform: {
enable: true,
config: {
onePxTransform: true,
unitPrecision: 5,
propList: ['*'],
selectorBlackList: [],
replace: true,
mediaQuery: false,
minPixelValue: 0
}
}
}
}
h5: {
postcss: {
pxtransform: {
enable: true,
config: {
onePxTransform: true,
unitPrecision: 5,
propList: ['*'],
selectorBlackList: [],
replace: true,
mediaQuery: false,
minPixelValue: 0
}
}
}
}
}
onePxTransform (Boolean)
Set up 1px Whether it needs to be converted
unitPrecision (Number)
REM The number of decimal places allowed in the unit .
propList (Array)
Attributes that allow conversion .
- Values need to be exact matches.
- Use wildcard
*to enable all properties. Example:['*'] - Use
*at the start or end of a word. (['*position*']will matchbackground-position-y) - Use
!to not match a property. Example:['*', '!letter-spacing'] - Combine the "not" prefix with the other prefixes. Example:
['*', '!font*']
selectorBlackList
Selectors in the blacklist will be ignored .
- If value is string, it checks to see if selector contains the string.
['body']will match.body-class
- If value is regexp, it checks to see if the selector matches the regexp.
[/^body$/]will matchbodybut not.body
replace (Boolean)
Replace directly instead of adding an additional one to cover .
mediaQuery (Boolean)
Allow media queries on px Unit conversion
minPixelValue (Number)
Set a minimum that can be converted px value
The configuration rule corresponds to config/index.js , for example :
/config/index.js
{
h5: {
publicPath: '/',
staticDirectory: 'static',
postcss: {
autoprefixer: {
enable: true
},
pxtransform: {
enable: true,
config: {
selectorBlackList: ['body']
}
}
}
},
mini: {
// ...
postcss: {
pxtransform: {
enable: true,
config: {
selectorBlackList: ['body']
}
}
}
}
}
CSS Ignore at compile time ( Filter )
Ignore individual properties
Currently the easiest way to ignore a single attribute , Namely px Units are in capital letters .
/* `px` is converted to `rem` */
.convert {
font-size: 16px; // converted to 1rem
}
/* `Px` or `PX` is ignored by `postcss-pxtorem` but still accepted by browsers */
.ignore {
border: 1Px solid; // ignored
border-width: 2PX; // ignored
}
Ignore style files
Include comments for headers /*postcss-pxtransform disable*/ The file of , The plug-in will not be processed .
Ignore style examples
When multiple lines of text in a style file are omitted, we usually use the following code :
.textHide {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp:2;
text-overflow: ellipsis;
overflow: hidden;
}
but Taro After compilation, there is less -webkit-box-orient: vertical; This style attribute , At this point we need to ignore this style
Ignore style methods 1 Join in CSS Comments force the declaration to ignore the next line
/* autoprefixer: ignore next */
-webkit-box-orient: vertical;
Ignore style methods 2 Join in CSS Comments force the declaration of multiple lines in the middle of the comment
/* autoprefixer: off */
-webkit-box-orient: vertical;
/* autoprefixer: on */
Ignore style methods 3 Write in line style
<View
style={
{
display: '-webkit-box',
'-webkit-box-orient': 'vertical',
'-webkit-line-clamp': 2,
'text-overflow': 'ellipsis',
overflow: 'hidden',
'line-height': 2
}}
>
This is what to omit this is what to omit this is what to omit
</View>Babel To configure
Taro Project Babel Configure the... Located in the root directory babel.config.js In file , By default, one is added preset:babel-preset-taro, It will add some commonly used according to the technology stack of the project presets and plugins.
babel.config.js
module.exports = {
presets: [
['taro', {/** Configuration item */}]
]
}
Developers can modify babel.config.js, modify babel-preset-taro Configuration item for , Or add what you want presets and plugins.
babel-preset-taro
babel-preset-taro According to the technology stack of the current project , Optionally use the following presets and plugins.
1. Universal
presets
@babel/preset-env@babel/preset-typescript(TypeScript Environmental Science )
plugins
@babel/plugin-transform-runtime@babel/plugin-proposal-decorators@babel/plugin-proposal-class-propertiesbabel-plugin-dynamic-import-node( Applet environment )
2. React
presets
@babel/preset-react
plugins
react-refresh/babel
3. Vue
presetes
@vue/babel-preset-jsx
4. Vue3
plugins
@vue/babel-plugin-jsx
Here is a detailed introduction babel-preset-taro Configuration item for .
reactJsxRuntime
NOTE
Only in the use of React Effective when .
The default value is :'automatic'
@babel/preset-react Of runtime Configuration item .
hot
NOTE
Only in the use of React Effective when .
The default value is :true
Whether to introduce react-refresh/babel To support the use of fast-refresh.
vueJsx
NOTE
Only in the use of Vue/Vue3 Effective when .
The default value is :true
type :true | false | object
Whether to use @vue/babel-preset-jsx(Vue) or @vue/babel-plugin-jsx(Vue3) To support the use of jsx.
When passing in a object when , Equivalent to setting to true, And the object Will be @vue/babel-preset-jsx(Vue) or @vue/babel-plugin-jsx(Vue3) Parameters of .
targets
The default value is :
{
ios: '9',
android: '5'
}
@babel/preset-env Of targets Configuration item .
useBuiltIns
The default value is :false
Valid values :'entry' | 'usage' | false
useBuiltIns: 'entry'
INFO
advantage : Global thoroughness polyfill, Even if the node_modules There is incompatible code for dependencies in , Can also run successfully .
shortcoming : Redundant code may be introduced 、 Affect global variables .
When it comes to 'entry' when , Will be able to @babel/preset-env Of useBuiltIns Option set to 'entry'、corejs Option set to '3'.
The developer needs to create an entry file app.js Introduction in core-js:
src/app.js
import "core-js"
Babel Will be based on targets, Introduce the corresponding core-js rely on . For example, the above code will be compiled as :
dist/app.js
import "core-js/modules/es.string.pad-start";
import "core-js/modules/es.string.pad-end";
// ...
Of course , Because at this time Taro hold
corejsSet to'3', So you can use[email protected]The ability to manually introduce on demand , For details, please see file .
useBuiltIns: 'usage'
INFO
advantage : Introduce on demand 、 Does not affect global variables .
shortcoming : By default... Will not be processed node_modules Dependency in , Manual configuration required babel-loader.
When it comes to 'usage' when , Will be able to @babel/plugin-transform-runtime Of corejs Option set to 3.
Be careful : Pass in
'usage'when , Taro Not used@babel/preset-envOfuseBuiltIns: 'usage'It USES@babel/plugin-transform-runtimeOfcorejs: 3. The reason lies in : One 、 When both are set at the same time, there will be a conflict . Two 、 The latter is relative to the former , Does not affect global variables .
useBuiltIns: false
When it comes to false when , Will be able to @babel/preset-env Of useBuiltIns Option set to false, No... Will be introduced at this time core-js.
loose
The default value is :false
At the same time @babel/preset-env、@babel/plugin-proposal-class-properties Of loose Configuration item .
debug
The default value is :false
@babel/preset-env Of debug Configuration item .
modules
The default value is :false
@babel/preset-env Of modules Configuration item .
spec
@babel/preset-env Of spec Configuration item .
configPath
@babel/preset-env Of configPath Configuration item .
include
@babel/preset-env Of include Configuration item .
exclude
@babel/preset-env Of exclude Configuration item .
shippedProposals
@babel/preset-env Of shippedProposals Configuration item .
forceAllTransforms
@babel/preset-env Of forceAllTransforms Configuration item .
decoratorsBeforeExport
@babel/plugin-proposal-decorators Of decoratorsBeforeExport Configuration item .
decoratorsLegacy
The default value is :true
@babel/plugin-proposal-decorators Of lagacy Configuration item .
absoluteRuntime
The default value is : Developer root directory node_modules Medium @babel/plugin-transform-runtime The path of .
type :string
@babel/plugin-transform-runtime Of absoluteRuntime Configuration item .
version
The default value is : Developer root directory node_modules Medium @babel/plugin-transform-runtime Version number of .
type :string
@babel/plugin-transform-runtime Of version Configuration item .
dynamic-import-node
NOTE
Redundant code can be removed , For some scenarios that strictly limit the size of the enclosure ( such as PWA etc. ) To be helpful to , But this also removes lazy loading of pages and components , Lead to app.js Too big .
Be careful :h5 The platform is off by default , Other platforms are enabled by default , The applet does not support dynamic loading by default , Can pass dynamic-import plug-in unit Provide this capability .
type :boolean
边栏推荐
- 【深度之眼吴恩达机器学习作业班第四期】Logistic Regression 逻辑回归总结
- 自动化测试 - uiautomator2框架应用 - 自动打卡
- 征文投稿丨使用轻量应用服务器搭建博客环境
- Improvement direction of programming ability
- Stm32 usart+dma usage based on Hal Library
- 【域渗透提权】CVE-2020-1472 NetLogon 权限提升漏洞
- [eye of depth wuenda machine learning homework class phase IV] regularization regularization summary
- Indextree and Application
- 华为云的AI深潜之旅
- Vulnhub's dc7 target
猜你喜欢

搭建jenkins环境并自动关联打包好的工程jar进行自动发布

RobotFramework学习笔记:Robot Framework和BrowserLibrary(PlayWright)简介

Protobuf binary file learning and parsing

Vulnhub's dc9 target

手撕二叉搜索树(Binary Search Tree)

关于SqlSugar的多对多的级联插入的问题(无法获取集合属性的id,导致无法维护中间表)

Un voyage profond d'IA dans Huawei Cloud

Vulnhub's DC8 target

SQL injection bypass (6)

在colaboratory上云端使用GPU训练(以YOLOv5举例)
随机推荐
《动手学深度学习》(一)-- 线性神经网络
电检码配置
Mongodb- connect to the database using the mongo/mongosh command line
C编译器 - 隐式函数声明
Flutter 文件读写-path_provider
Product security - small vulnerabilities cause big problems
SQL Server 开启cdc
Common MySQL errors and solutions summarized painstakingly (I)
JSP learning part
【修复收藏功能、更新登录接口】知识付费小程序、博客小程序、完整版开源源码、资源变现小程序,带299整站资源数据
基于Sophus的Ceres优化
【深度之眼吴恩达机器学习作业班第四期】逻辑回归编程实现
数组知识点小结
js:Array.reduce累加计算、合并数组
在iframe标签中操作外层dom
Indextree and Application
MySQL中有哪些约束?(实例验证)
JS XOR obfuscation code
Oracle batch insert data - insert ethnic data
小白大战指针 (上)