配置小程序云开发 TypeScript 环境
1. 检查本地 nodejs 环境
2. 安装 TypeScript npm install typescript --save-dev
3. 初始化/配置 TypeScript
3.1 初始化 ./node_modules/.bin/tsc --init
3.2 修改tsconfig.json
配置
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"typeRoots": ["./typings"],
"esModuleInterop": true,
"strict": true,
"skipLibCheck": true
},
"include": ["./miniprogram/**/*.ts", "./cloudfunctions/**/*.ts"],
"exclude": ["node_modules"]
}
3.3 添加 TypeScript .d.ts 文件
- 在项目根目录新建文件夹
typings
(与 tsconfig.json>compilerOptions>typeRoots 配置一致) - 复制 https://github.com/wechat-miniprogram/api-typings/tree/master/types 目录下的所有文件到 typings 文件夹
- 如果无法访问,也可从这里下载: typings.zip
4. 配置编译命令
4.1 在package.json
添加scripts
命令
"tsc": "node ./node_modules/typescript/lib/tsc.js"
4.2 修改project.config.json
,添加自定义处理命令
{
"scripts": {
"beforeCompile": "npm run tsc",
"beforePreview": "npm run tsc",
"beforeUpload": "npm run tsc"
}
}
4.3 在“微信开发者工具”中启用自定义处理命令
示例
1. 调用微信云函数获取微信步数
// 小程序端,获取微信步数相关数据
async getWxRunData(): Promise {
return new Promise((resolve, reject) => {
wx.getWeRunData({
success: resolve,
fail: reject
});
});
}
// 云函数 getOpenData
export const main = async (event: { cloudID: string }) => {
const { cloudID } = event;
...
// 通过云调用直接获取开放数据
const openData = await cloud.getOpenData({
list: [cloudID]
})
return {
errCode: 0,
errMsg: '获取成功',
data: openData.list[0].data
}
...
}
2. 云函数调用数据库存储用户步数
// 小程序端
await wx.cloud.callFunction({
name: 'createUserStep',
data: {
step
}
});
// 云函数 createUserStep
const { step } = event;
const wxContext = cloud.getWXContext();
const openid = wxContext.OPENID;
const userStepQuery = {
openid,
date: db.RegExp({
regexp: `^${getCurrentDate()}`,
})
}
const userStep = await userStepCollection.where(userStepQuery).get() as cloud.DB.IQueryResult;
if (userStep.data.length > 0) {
userStepCollection.doc(userStep.data[0]._id!).update({ data: { step } })
} else {
userStepCollection.add({
data: {
step,
openid,
date: getCurrentDate()
}
})
}
return userStep.data;
Github地址:https://github.com/greywen/MiniprogramCloudDevelopmentTemplate-TypeScript