Hono CLI

repository·main·Indexed 43 days ago

https://github.com/honojs/cli

A specialized toolset for developing, testing, and optimizing Hono applications. It provides commands to access documentation via `docs` and `search`, test routes without a full server using `request`, start a server with `serve`, and reduce bundle size through aggressive tree-shaking and API removal with `optimize`.

Tokens
5.6K
Snippets
21
Records
22
Agent score
55%

What's inside Hono CLI

  1. Use the Hono CLI

    main

    The hono command provides a suite of tools for interacting with Hono applications, including documentation access, code optimization, request testing, and server management.

    Available commands include:

    • docs: Access documentation summaries.
    • optimize: Generate optimized Hono applications.
    • search: Search through documentation.
    • request: Send requests to a running Hono app.
    • serve: Start a Hono server.

    You can check the installed version using the -v or --version flag.

    hono --version
  2. How the `optimize` command works

    main

    The optimize command uses esbuild with custom plugins to perform tree-shaking at a more aggressive level than standard bundlers. It works through several stages:

    1. Static Analysis: It first performs a build pass to analyze the application's routes and identify which Hono methods and Context response utilities are actually invoked in your code.
    2. API Removal Logic:
      • Request Body APIs: If the application only contains GET, HEAD, or OPTIONS routes, the command removes request body parsing methods (e.g., parseBody, json, formData) from the HonoRequest class.
      • Hono Core APIs: It identifies unused methods on the Hono class (like mount or route) and removes them from HonoBase.
      • Context Response APIs: It scans your source code for unused methods on the Context object (like html or redirect) and removes them from the Context class.
    3. Router Optimization: It attempts to use PreparedRegExpRouter from hono/router/reg-exp-router if available in the environment to optimize route matching based on the serialized route parameters found during analysis.
    4. Final Bundle: It executes a final esbuild pass with the modified Hono source code to produce the optimized, bundled output.
  3. Format and include response headers

    main

    By default, the request command prints the response body to stdout. You can modify this behavior using the following flags:

    • --json: If the response content-type is JSON, this flag will format the output as a JSON object containing the status, body, and headers.
    • --include: Includes the HTTP status and headers in the output before the body.
    • --head: Shows only the HTTP status and headers, omitting the body.
    # View only headers
    hono request src/index.ts -I
    
    # View headers and body together
    hono request src/index.ts -i
    
    # Get a structured JSON object of the whole response
    hono request src/index.ts -J
  4. Save request responses to files

    main

    You can capture the output of a request and save it directly to a file using the --output or --remote-name flags.

    • Use -o, --output <file> to specify a specific filename for the saved response.
    • Use -O, --remote-name to automatically name the file based on the request path and the response's content-type.
    hono request src/index.ts -P /api/data -o response.json
  5. Configure tsdown for Hono CLI builds

    main

    The Hono CLI uses tsdown for its build process. You can configure the build behavior using defineConfig from the tsdown package. Key configuration options include:

    • entry: An array of entry point files.
    • format: The output module format (e.g., ['esm']).
    • dts: Boolean to enable/disable declaration file generation.
    • sourcemap: Boolean to enable/disable sourcemaps.
    • clean: Boolean to clean the output directory before building.
    • minify: Boolean to enable/disable minification.
    • banner: An object containing strings to prepend to the output files (e.g., js for the shebang line #!/usr/bin/env node).
    • target: Specifies the compilation target.
    • outExtensions: A function that receives the format and returns an object mapping extensions to their desired output suffixes.
    • inlineOnly: An array of package names to be inlined into the output bundle.
    import { defineConfig } from 'tsdown'
    
    export default defineConfig({
      entry: ['src/cli.ts'],
      format: ['esm'],
      dts: false,
      sourcemap: false,
      clean: true,
      minify: false,
      banner: {
        js: '#!/usr/bin/env node',
      },
      target: false,
      outExtensions({ format }) {
        return {
          js: format === 'es' ? '.js' : '.cjs',
        }
      },
      inlineOnly: ['@babel/parser', '@jridgewell/sourcemap-codec', 'magic-string'],
    })
  6. Reference: `hono optimize` options

    main

    Options for the hono optimize command to control the bundling and optimization process.

    -o, --outfile <outfile>                Output file
    -m, --minify                          minify output file
    -t, --target [target]                 environment target
    --no-request-body-api-removal          Disable request body API removal optimization
    --no-context-response-api-removal      Disable response utility API removal from Context object
    --no-hono-api-removal                  Disable Hono API removal optimization
  7. Reference: `hono serve` options

    main

    Options for the hono serve command to configure the running server.

    -p, --port <port>       Port number (default: 7070)
    --show-routes           Show registered routes
    --use <middleware>      Use middleware (can be used multiple times)
    -e, --external <package> Mark package as external (can be used multiple times)
  8. Reference: `hono request` options

    main

    Options for the hono request command to control the HTTP request sent to the application.

    -P, --path <path>      Request path (default: "/")
    -X, --method <method>   HTTP method (default: GET)
    -d, --data <data>       Request body data
    -H, --header <header>   Custom headers (can be used multiple times)
    -w, --watch             Watch for changes and resend request
    -J, --json              Output response as JSON
    -o, --output <file>     Write to file instead of stdout
    -O, --remote-name       Write output to file named as remote file
    -i, --include           Include protocol and headers in the output
    -I, --head              Show only protocol and headers in the output
    -e, --external <package> Mark package as external (can be used multiple times)
  9. Start a Hono server with `serve`

    main

    The hono serve command starts a specialized server for Hono applications with built-in TypeScript and JSX support. You can specify a port, show registered routes, and inject middleware directly via the CLI.

    # Start server with default empty app
    hono serve
    
    # Start server on specific port
    hono serve -p 3000 src/app.ts
    
    # Start server and show routes
    hono serve --show-routes src/app.ts
    
    # Start server with middleware
    hono serve --use 'cors()' src/app.ts
    
    # Start server with multiple middleware
    hono serve --use 'cors()' --use 'logger()' src/app.ts
    
    # Start server with external packages
    hono serve -e pg -e prisma src/app.ts
  10. Generate an optimized Hono app with `optimize`

    main

    The hono optimize command generates an optimized Hono class and exports a bundled file. It applies several tree-shaking optimizations to reduce bundle size:

    • Request body API removal: Removes c.req.json(), c.req.formData(), etc., if the app only uses GET, HEAD, or OPTIONS.
    • Context response API removal: Removes unused response utilities like c.body(), c.json(), c.text(), etc.
    • Hono API removal: Removes unused initialization methods like route, mount, and fire.

    You can disable these optimizations using specific flags.

    # Generate an optimized Hono class and export bundled file to dist/index.js
    hono optimize
    
    # Specify entry file and output file
    hono optimize -o dist/app.js src/app.ts
    
    # Export bundled file with minification
    hono optimize -m
    
    # Disable specific optimizations
    hono optimize -m --no-request-body-api-removal
  11. Send requests to a Hono app with `request`

    main

    The hono request command sends HTTP requests to your Hono application using the built-in app.request() method. This is ideal for testing routes without starting a full server. It supports custom paths, methods, data, and headers.

    # GET request to default app root (uses src/index.ts or src/index.tsx)
    hono request
    
    # GET request to specific path
    hono request -P /users/123
    
    # POST request with data
    hono request -P /api/users -X POST -d '{"name":"Alice"}'
    
    # Request with custom headers
    hono request -P /api/protected \
      -H 'Authorization: Bearer token' \
      -H 'User-Agent: MyApp' \
      src/your-app.ts
    
    # Request with external packages (useful for Node.js native modules)
    hono request -e pg -e dotenv src/your-app.ts