swordjs / sword-framework

A small and flexible for serverless nodejs framework 💗
25 stars 3 forks source link

[RFC-v2.0] Support AutoImport #22

Open seho-dev opened 1 year ago

seho-dev commented 1 year ago

AutoImport function is provided by unImport, you can add dependencies for auto import in sword.config.ts, for example, I export a library function like this:

  autoImport: {
    presets: [
      {
        from: '@swordjs/h3',
        imports: ['sendError']
      }
    ]
  }

In the ts file, you'll be able to use sendError directly without having to import it manually; this is important for functions that frequently require manual import, such as useApi, so sword.js-cli has a bunch of automatic import APIs built in:

const autoImportsPresets: Preset[] = [
  {
    from: '@swordjs/sword-framework'.
    imports: ['useApi', 'useApp', 'usePipeline', 'usePlugin', 'useGetApiMap', 'usePlatform', 'usePlatformHook', 'useIsDev', 'useIsProd']
  }
].

This allows us to quickly write code like this:

import { ReqQuery, ReqParams, Res } from '. /proto'.

export default useApi<{
  query: ReqQuery.
  params: ReqParams.
  res: Res.
}>({
  handler: async (ctx) => {
    console.log(sendError).
    return {
      message: 'hello world'
    }.
  }
}).

And the auto-import.d.ts file will be generated as a type hint under the src folder each time dev is executed.

Since the dev environment of sword.js is using esbuild-register to open a new sub-process to execute functions, and also enjoy auto-import, we changed the source code of esbuild-register because we want to keep the dev and prod development experience consistent