环境:
# 系统 Windows11
# Node 18.17.0
一、安装Taro
# 使用 npm 安装 CLI
$ npm install -g @tarojs/cli
# OR 使用 yarn 安装 CLI
$ yarn global add @tarojs/cli
# OR 安装了 cnpm,使用 cnpm 安装 CLI
$ cnpm install -g @tarojs/cli
二、项目初始化
taro init
? 请输入项目名称! Test
? 请输入项目介绍 test
? 请选择框架 (Use arrow keys)
? 请选择框架 React
? 是否需要使用 TypeScript ? (Y/n) y
? 是否需要使用 TypeScript ? Yes
? 请选择 CSS 预处理器(Sass/Less/Stylus) (Use arrow keys)
? 请选择 CSS 预处理器(Sass/Less/Stylus) Sass
? 请选择编译工具 (Use arrow keys)
? 请选择编译工具 Webpack5
? 请选择包管理工具 (Use arrow keys)
? 请选择包管理工具 yarn
? 请选择模板源 (Use arrow keys)
? 请选择模板源 Gitee(最快)
-
框架选择React, PReact虽然很小但是坑很多
三、基础配置
环境变量
.env.development # 在 development 模式时被载入
.env.production # 在 production 模式时被载入
-
请注意,只有以 TARO_APP_ 开头的变量将通过 webpack.DefinePlugin 静态地嵌入到客户端侧的代码中。这是为了避免和系统内置环境变量冲突。
-
如果需要在src目录下使用process.env,需要在config->index.ts中声明
defineConstants: {
'process.env': JSON.stringify(process.env),
},
单位转换配置
设计稿使用的是375的宽度,px转rpx是x2
designWidth: 375,
deviceRatio: {
375: 2,
640: 2.34 / 2,
750: 1,
828: 1.81 / 2,
},
其他配置
# 引用使用@
alias: { '@': './src' },
请求拦截器配置
import Taro from '@tarojs/taro';
import { getCookieItem } from '@/utils/common';
//网络请求拦截器
const interceptor = function (chain) {
const requestParams = chain.requestParams;
const cookie = Taro.getStorageSync('cookie');
const token = getCookieItem('csrftoken', cookie);
requestParams.header = {
Cookie: Taro.getStorageSync('cookie') || '',
'X-CSRFToken': token || '',
...requestParams.header,
};
return chain.proceed(requestParams).then((res) => {
return res;
});
};
Taro.addInterceptor(interceptor);
let API_ENDPOINT = '';
const env_info = Taro.getAccountInfoSync().miniProgram.envVersion;
if (env_info === 'develop' || env_info === 'release') {
API_ENDPOINT = process.env.TARO_APP_API_ENDPOINT as string;
}
if (env_info === 'trial') {
API_ENDPOINT = process.env.TARO_APP_STAGING_API as string;
}
const request = async (method, url, data, config) => {
const contentType = config?.headers?.['Content-Type'] || 'application/json';
const option = {
method,
isShowLoading: config.isShowLoading,
url: API_ENDPOINT + url,
data: data,
header: {
'Content-type': contentType,
},
};
const resp = await Taro.request(option);
if (resp.header['Set-Cookie']) {
Taro.setStorageSync('cookie', resp.header['Set-Cookie'].replace(/,/g, ';'));
}
return resp;
};
export default {
get: (url, params = {}, config = {}) => {
return request('GET', url, params, config);
},
post: (url, data, config = {}) => {
return request('POST', url, data, config);
},
put: (url, data, config = {}) => {
return request('PUT', url, data, config);
},
delete: (url, params = {}, config = {}) => {
return request('DELETE', url, params, config);
},
patch: (url, data, config = {}) => {
return request('PATCH', url, data, config);
},
};
四、项目启动和编译
-
修改package.json,因为只有微信小程序一端,直接使用--type weapp
"build": "taro build --type weapp",
"dev": "taro build --type weapp --watch",