創建項目
在微信開發者工具創建項目,在語言中選擇 TypeScript
改造項目
編輯 package.json
文件,修改 miniprogram-api-typings
和 typescript
版本
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
{ "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 配置項
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
{ "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 文件,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
// 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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都支持
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
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
到此這篇關于typescript編寫微信小程序創建項目的方法的文章就介紹到這了,更多相關typescript開發微信小程序內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://www.cnblogs.com/plum-nikolas/archive/2021/01/28/14339990.html