使用TypeScript开发微信小程序(云开发)-入门篇

配置小程序云开发 TypeScript 环境

1. 检查本地 nodejs 环境

使用TypeScript开发微信小程序(云开发)-入门篇

2. 安装 TypeScript npm install typescript --save-dev

使用TypeScript开发微信小程序(云开发)-入门篇

3. 初始化/配置 TypeScript

3.1 初始化 ./node_modules/.bin/tsc --init

使用TypeScript开发微信小程序(云开发)-入门篇

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 文件
  1. 在项目根目录新建文件夹typings(与 tsconfig.json>compilerOptions>typeRoots 配置一致)
  2. 复制 https://github.com/wechat-miniprogram/api-typings/tree/master/types 目录下的所有文件到 typings 文件夹
  3. 如果无法访问,也可从这里下载: typings.zip

使用TypeScript开发微信小程序(云开发)-入门篇

4. 配置编译命令

4.1 在package.json添加scripts命令
"tsc": "node ./node_modules/typescript/lib/tsc.js"

使用TypeScript开发微信小程序(云开发)-入门篇

4.2 修改project.config.json,添加自定义处理命令
{   "scripts": {     "beforeCompile": "npm run tsc",     "beforePreview": "npm run tsc",     "beforeUpload": "npm run tsc"   } }

使用TypeScript开发微信小程序(云开发)-入门篇

4.3 在“微信开发者工具”中启用自定义处理命令

使用TypeScript开发微信小程序(云开发)-入门篇

示例

1. 调用微信云函数获取微信步数

// 小程序端,获取微信步数相关数据 async getWxRunData(): Promise<WechatMiniprogram.GetWeRunDataSuccessCallbackResult> {   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;

使用TypeScript开发微信小程序(云开发)-入门篇

Github地址:https://github.com/greywen/MiniprogramCloudDevelopmentTemplate-TypeScript

参考:
https://www.cnblogs.com/xiabings/p/17171277.html

发表评论

评论已关闭。

相关文章