配置小程序云开发 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"<br>
复制代码
4.2 修改project.config.json,添加自定义处理命令
- {
- "scripts": {
- "beforeCompile": "npm run tsc",
- "beforePreview": "npm run tsc",
- "beforeUpload": "npm run tsc"
- }
- }<br>
复制代码
4.3 在“微信开发者工具”中启用自定义处理命令
示例
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;<br><br>
复制代码
Github地址:https://github.com/greywen/MiniprogramCloudDevelopmentTemplate-TypeScript
参考:
https://www.cnblogs.com/xiabings/p/17171277.html
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |