創建專案
在微信開發者工具創建專案,在語言中選擇 TypeScript
改造專案
- 編輯
package.json檔案,修改miniprogram-api-typings和typescript版本
{
"name": "miniprogram-ts-quickstart",
"version": "1.0.0",
"description": "",
"scripts": {
"compile": "./node_modules/typescript/bin/tsc",
"tsc": "node ./node_modules/typescript/lib/tsc.js"
},
"keywords": [],
"author": "",
"license": "",
"dependencies": {
},
"devDependencies": {
"typescript": "^4.1.3",
"miniprogram-api-typings": "^2.12.1-beta.0"
}
}
- 編輯 tsconfig.json 檔案, 修改 lib 為 ["esnext"],支持最新語法, 洗掉 typeRoots 配置項
{
"compilerOptions": {
"strictNullChecks": true,
"noImplicitAny": true,
"module": "CommonJS",
"target": "ES5",
"allowJs": false,
"experimentalDecorators": true,
"noImplicitThis": true,
"noImplicitReturns": true,
"alwaysStrict": true,
"inlineSourceMap": true,
"inlineSources": true,
"noFallthroughCasesInSwitch": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"strict": true,
"removeComments": true,
"pretty": true,
"strictPropertyInitialization": true,
"lib": ["esnext"]
},
"include": [
"./**/*.ts"
],
"exclude": [
"node_modules"
]
}
-
執行
npm install -
洗掉專案下 typings 目錄, 的 復制 node_modules 下 miniprogram-api-typings 的 types 檔案到專案根目錄
-
在 miniprogram 下創建 interface 目錄并創建 IAppOption.ts 檔案,最后編輯 app.ts 檔案,
// IAppOption.ts
export default interface IAppOption {
globalData: {
text: string;
}
}
// app.ts
import IAppOption from "./interface/IAppOption";
App<IAppOption>({
globalData: {
text: "Hello,Word!"
},
onLaunch() {
}
})
- 在 詳細 -> 本地設定 -> 除錯基礎庫,直接選擇最新的
使用 Promise 化的微信小程式api
以前可以通過 miniprogram-api-promise 這個包來完成 api Promise 化,或者自己寫
現在可以直接使用,比如 wx.getStorageInfo ,在 lib.wx.api.d.ts 中回傳了 PromisifySuccessResult
PromisifySuccessResult 回傳了Promise
getStorageInfo<TOption extends GetStorageInfoOption>(
option?: TOption
): PromisifySuccessResult<TOption, GetStorageInfoOption>
type PromisifySuccessResult<
P,
T extends AsyncMethodOptionLike
> = P extends { success: any }
? void
: P extends { fail: any }
? void
: P extends { complete: any }
? void
: Promise<Parameters<Exclude<T['success'], undefined>>[0]>
兩種用法,大多數api都支持
wx.getStorageInfo({
success: () => {
console.log('成功執行')
},
fail: () => {
console.log('失敗執行')
},
complete: () => {
console.log('介面呼叫結束')
}
})
wx.getStorageInfo().then(() => {
console.log('成功執行')
}).catch(() => {
console.log('失敗執行')
}).finally(() => {
console.log('介面呼叫結束')
})
原始碼: https://github.com/NikolasSky/ts-miniprogram/tree/master/ts-miniprogram-base
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/253884.html
標籤:HTML5
上一篇:Web儲存
下一篇:騰訊面試題整理(其一)
