Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[RFC-v2.0] Support AutoImport #22

Open
seho-dev opened this issue Apr 2, 2023 · 1 comment
Open

[RFC-v2.0] Support AutoImport #22

seho-dev opened this issue Apr 2, 2023 · 1 comment

Comments

@seho-dev
Copy link
Contributor

seho-dev commented Apr 2, 2023

No description provided.

@seho-dev seho-dev converted this from a draft issue Apr 2, 2023
@seho-dev seho-dev moved this from Todo to In Progress in Sword.js v2.0 Apr 2, 2023
@seho-dev seho-dev moved this from In Progress to Done in Sword.js v2.0 Apr 2, 2023
seho-dev added a commit that referenced this issue Apr 2, 2023
@seho-dev
Copy link
Contributor Author

seho-dev commented Apr 2, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: Done
Development

No branches or pull requests

1 participant