Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

🍳 Generate TypeScript definition files(d.ts) for Egg

License

NotificationsYou must be signed in to change notification settings

eggjs/egg-ts-helper

Repository files navigation

NPM versionNode.js CIPackage QualityTest coverageNPM download

A simple tool for creatingd.ts inegg application. Injectingcontroller, proxy, service, etc. to definition type of egg ( such asContextApplication etc. ) byDeclaration Merging, and making IntelliSense works in both egg-js and egg-ts.

Install

open your application and install.

npm i egg-ts-helper --save-dev

QuickStart

Open your egg application, executing ets bynpx

npx ets

Watching files by-w flag.

npx ets -w

egg-ts-helper has build-in inegg-bin, You can easily to use it by

egg-bin dev --dts

or add configurationegg.declarations inpackage.json

CLI

$ ets -h  Usage: bin [commands] [options]  Options:    -v, --version           output the version number    -w, --watch             Watching files, d.ts would recreated while file changed    -c, --cwd [path]        Egg application base dir (default: process.cwd)    -C, --config [path]     Configuration file, The argument can be a file path to a valid JSON/JS configuration file.(default: {cwd}/tshelper    -o, --oneForAll [path]  Create a d.ts import all types (default: typings/ets.d.ts)    -s, --silent            Running without output    -i, --ignore [dirs]     Ignore generator, your can ignore multiple dirs with comma like: -i controller,service    -e, --enabled [dirs]    Enable generator, your can enable multiple dirs with comma like: -e proxy,other    -E, --extra [json]      Extra config, the value should be json string    -h, --help              output usage information  Commands:    clean                   Clean js file while it has the same name ts/tsx file    init <type>             Init egg-ts-helper in your existing project

Configuration

nametypedefaultdescription
cwdstringprocess.cwdegg application base dir
typingsstring{cwd}/typingstypings dir
caseStylestringFunctionloweregg case style(lower,upper,camel) or(filename) => {return 'YOUR_CASE'}
silentbooleanfalseignore logging
watchbooleanfalsewatch file change or not, default totrue inregister
watchOptionsobjectundefinedchokidaroptions
autoRemoveJsbooleantrueauto remove same name js on startup
configFilestring{cwd}/tshelper.(jsjson)
generatorConfigobjectgenerator configuration( watchDirs has been deprecated )

You can configure the options above in./tshelper.js./tshelper.json orpackage.json.

Intshelper.js

// {cwd}/tshelper.jsmodule.exports={generatorConfig:{model:{enabled:true,generator:"function",interfaceHandle:"InstanceType<{{ 0 }}>"},}}

Intshelper.json

// {cwd}/tshelper.json{"generatorConfig": {"model": {"enabled":true,"generator":"function","interfaceHandle":"InstanceType<{{ 0 }}>"    },  }}

Inpackage.json

// {cwd}/package.json{"egg": {"framework":"egg","tsHelper": {"generatorConfig": {"model": {"enabled":true,"generator":"function","interfaceHandle":"InstanceType<{{ 0 }}>"        }      }    }  }}

or usedot-prop

// {cwd}/package.json{"egg": {"framework":"egg","tsHelper": {"generatorConfig.model": {"enabled":true,"generator":"function","interfaceHandle":"InstanceType<{{ 0 }}>"      }    }  }}

Also you can pass options by env ( support since 1.22.0 )

  • ETS_CWD: cwd
  • ETS_FRAMEWORK: framework
  • ETS_TYPINGS: typings
  • ETS_CASE_STYLE: caseStyle
  • ETS_AUTO_REMOVE_JS: autoRemoveJs
  • ETS_THROTTLE: throttle
  • ETS_WATCH: watch
  • ETS_SILENT: silent
  • ETS_CONFIG_FILE: configFile

Custom Loader

Support since 1.24.0

egg-ts-helper support customLoader configuration of egg. seeeggjs/egg#3480

Configure inconfig.default.ts

'use strict';import{EggAppConfig,PowerPartial}from'egg';exportdefaultfunction(appInfo:EggAppConfig){constconfig={}asPowerPartial<EggAppConfig>;config.keys=appInfo.name+'123123';config.customLoader={model:{directory:'app/model',inject:'app',caseStyle:'upper',},};return{    ...configas{},    ...bizConfig,};}

egg-ts-helper will auto create the d.ts for files underapp/model

// This file is created by egg-ts-helper@1.24.1// Do not modify this file!!!!!!!!!import'egg';typeAutoInstanceType<T,U=Textends(...args:any[])=>any ?ReturnType<T> :T>=Uextends{new(...args:any[]):any} ?InstanceType<U> :U;importExportCastlefrom'../../../app/model/Castle';importExportUserfrom'../../../app/model/User';declare module'egg'{interfaceApplication{model:T_custom_model;}interfaceT_custom_model{Castle:AutoInstanceType<typeofExportCastle>;User:AutoInstanceType<typeofExportUser>;}}

And you can easily to use it in your code.

image

Generator

If you are usingloader.loadToApp orloader.loadToContext to load the instance, you should use generator config.

Example

Creatingd.ts for files underapp/model. You should add configgeneratorConfig.model in your config file.

// ./tshelper.jsmodule.exports={generatorConfig:{model:{directory:'app/model',// files directory.// pattern: '**/*.(ts|js)', // glob pattern, default is **/*.(ts|js). it doesn't need to configure normally.// ignore: '', // ignore glob pattern, default to empty.generator:'class',// generator name, eg: class、auto、function、objectinterface:'IModel',// interface namedeclareTo:'Context.model',// declare to this interface// watch: true, // whether need to watch files// caseStyle: 'upper', // caseStyle for loader// interfaceHandle: val => `ReturnType<typeof ${val}>`, // interfaceHandle// trigger: ['add', 'unlink'], // recreate d.ts when receive these events, all events: ['add', 'unlink', 'change']}}}

The configuration can create d.ts as below.

Attention, The type will merge into egg without any pre handling if the generator field isclass, If you dont know how it works, just usinggenerator: 'auto' instead.

importStationfrom'../../../app/model/station';// <-- find all files under app/model and import then.declare module'egg'{interfaceContext{// <-- Context is reading from `declareTo`model:IModel;// <-- IModel is reading from `interface`, It will create a random interface if this field is empty}interfaceIModel{// <-- The same as above.Station:Station;// <-- Merging `Station` to IModel so we can use `ctx.model.Station` in code.}}

Effect of different options

interfacestring

interface set toIOther.

interfaceIOther{Station:Station;}

It will use random interface ifinterface is not set.

interfaceT100{Station:Station;}

Attentions: Must setdeclareTo ifinterface is not set.

generatorstring

The name of generator, available value isclassfunctionobjectauto.

generator: 'class'

the types created byclass generator as below

interfaceIModel{Station:Station;}

It's suitable for module wrote like this

exportdefaultclassXXXControllerextendsController{}

generator: 'function' ( Support since1.16.0 )

the types created byfunction generator as below

interfaceIModel{Station:ReturnType<typeofStation>;// Using ReturnType to get return type of function.}

It's suitable for module like this

exportdefault()=>{return{};}

generator: 'object' ( Support since1.16.0 )

the types created byobject generator as below.

interfaceIModel{Station:typeofStation;}

It's suitable for module like this

exportdefault{}

generator: 'auto' ( Support since1.19.0 )

the types created byauto generator as below. It will check types automatically.

typeAutoInstanceType<T,U=Textends(...args:any[])=>any ?ReturnType<T> :T>=Uextends{new(...args:any[]):any} ?InstanceType<U> :U;interfaceIModel{Station:AutoInstanceType<typeofStation>;}

It's suitable for every module in above.

interfaceHandlefunction|string

If you cannot find suitable generator in above, you can config the type by this field.

module.exports={generatorConfig:{model:{      ...interfaceHandle:val=>`${val} & { [key: string]: any }`,}}}

The generated typings.

interfaceIModel{Station:Station&{[key:string]:any};}

The type ofinterfaceHandle can bestring ( Support since1.18.0 )

module.exports={generatorConfig:{model:{      ...interfaceHandle:'{{ 0 }} & { [key: string]: any }',}}}

The generated typings are the same as above.{{ 0 }} means the first argument in function.

caseStylefunction|string

caseStyle can set toloweruppercamel or function

declareTostring

Declaring interface to definition of egg. ( Support since1.15.0 )

declareTo set toContext.model , and you can get intellisense byctx.model.xxx

importStationfrom'../../../app/model/station';declare module'egg'{interfaceContext{model:IModel;}interfaceIModel{Station:Station;}}

declareTo set toApplication.model.subModel, and you can get intellisense byapp.model.subModel.xxx

importStationfrom'../../../app/model/station';declare module'egg'{interfaceApplication{model:{subModel:IModel;}}interfaceIModel{Station:Station;}}

Defining custom generator

// ./tshelper.js// custom generatorfunctionmyGenerator(config,baseConfig){// config.dir       dir// config.dtsDir    d.ts dir// config.file      changed file// config.fileList  file listconsole.info(config);console.info(baseConfig);// return type can be object or array { dist: string; content: string } | Array<{ dist: string; content: string }>// egg-ts-helper will remove dist file when content is undefined.return{dist:'d.ts file url',content:'d.ts content'}}module.exports={generatorConfig:{model:{directory:'app/model',generator:myGenerator,trigger:['add','unlink'],}}}

or define generator to other js.

// ./my-generator.jsmodule.exports.defaultConfig={// default watchDir config}// custom generatormodule.exports=(config,baseConfig)=>{// config.dir       dir// config.dtsDir    d.ts dir// config.file      changed file// config.fileList  file listconsole.info(config);console.info(baseConfig);// return type can be object or array { dist: string; content: string } | Array<{ dist: string; content: string }>// egg-ts-helper will remove dist file when content is undefined.return{dist:'d.ts file url',content:'d.ts content'}}

configure intshelper.js orpackage.json

// ./tshelper.jsmodule.exports={generatorConfig:{model:{directory:'app/model',generator:'./my-generator',trigger:['add','unlink'],}}}

Demo

egg-ts-helper can works in bothts andjs egg project.

TS demo:https://github.com/whxaxes/egg-boilerplate-d-ts

JS demo:https://github.com/whxaxes/egg-boilerplate-d-js

License

MIT

Contributors

Contributors

Made withcontributors-img.

About

🍳 Generate TypeScript definition files(d.ts) for Egg

Resources

License

Stars

Watchers

Forks

Contributors16


[8]ページ先頭

©2009-2025 Movatter.jp