在調整typescript項目結構,全局變量儘可能少用,但仍是必不可少的,既要合理的引入,又要能用上vscode的智能提示。上篇日誌已經記錄了,在vscode中開發,全局變量的定義與聲名是分開的,要作好對應。mysql
├── src │ ├── app.ts │ ├── common │ │ └── globUtils.ts │ ├── config │ │ └── log4js.ts │ ├── globals.d.ts │ ├── index.ts │ └── inits │ ├── global.ts │ └── tasks.ts ├── tsconfig.json ├── tslint.json
export default class GlobUtils { isDev() { return global.NODE_ENV !== 'prod' } }
注意事項:git
import * as lodash from 'lodash' import * as Bluebird from 'bluebird' import GlobUtils from '../common/globUtils' export default { async init() { Object.assign(global, { ROOT_PATH: process.cwd(), NODE_ENV: process.env.NODE_ENV || 'dev', //dev - 開發; prod - 生產; test - 測試; Promise: Bluebird, __: lodash, globUtils: new GlobUtils(), }) } }
注意事項:github
import { Logger } from 'log4js' import GlobUtils from './common/globUtils' import * as lodash from 'lodash' type LODASH = typeof lodash declare global { namespace NodeJS { interface Global { logger: Logger, NODE_ENV: string, ROOT_PATH: string, globUtils: GlobUtils, __: LODASH, } } }
注意事項:sql
用@types/bluebird-global替換@types/bluebird,便可完成替換。咱們只須要在代碼定義中增長它的定義就行了。
注意事項:typescript
代碼是這個項目的基礎,此項目我準備將express+mysql的成功經驗移植到koa2中來。express
https://github.com/zhoutk/gels
git clone https://github.com/zhoutk/gels cd gels git checkout 9ea084f yarn tsc -w 用vscode打開項目,並按F5運行
終於邁入typescript坑中,痛並快樂着!json