"Si un trabajador quiere hacer bien su trabajo, primero debe afilar sus herramientas." - Confucio, "Las Analectas de Confucio. Lu Linggong"
Página delantera > Programación > [Paquete diario] dedente

[Paquete diario] dedente

Publicado el 2025-02-06
Navegar:399

[Daily Package] dedent

La vida antes de conocer el dedente

¿Alguna vez ha intentado escribir párrafo de múltiples líneas en plantilla literal, pero se ha dado cuenta de que conserva la sangría, que terminó usando la adición de cadena con \ n?

function explain() {
  const description = `
    - 200 OK
      The request succeeded. The result meaning of "success" depends on the HTTP method:

      * GET: The resource has been fetched...
      * HEAD: The representation headers are...
      * PUT or POST: The resource describing...
      * TRACE: The message body contains the...
  `

  console.log(description)
}

explain()
$ bun index.ts

    - 200 OK
      The request succeeded. The result meaning of "success" depends on the HTTP method:

      * GET: The resource has been fetched...
      * HEAD: The representation headers are...
      * PUT or POST: The resource describing...
      * TRACE: The message body contains the...

espera, ¿necesito eliminar las hendiduras?
Nah. No puedo renunciar a mi código bellamente formateado.

function explain() {
  const description = '- 200 OK\n'  
    'The request succeeded. The result meaning of "success" depends on the HTTP method:\n\n'  
    '  * GET: The resource has been fetched...\n'  
    '  * HEAD: The representation headers are...\n'  
    '  * PUT or POST: The resource describing...\n'  
    '  * TRACE: The message body contains the...\n'

  console.log(description)
}

explain()

Tomaré eso. ?

Por este motivo, el texto multiline siempre es un dolor de cabeza para mí.

Ahora sabes dedente

Pero ahora, ya no tiene que negociar contigo mismo. Solo use dedente.

import dedent from 'dedent'

function explain() {
  const description = dedent`
    - 200 OK
      The request succeeded. The result meaning of "success" depends on the HTTP method:

      * GET: The resource has been fetched...
      * HEAD: The representation headers are...
      * PUT or POST: The resource describing...
      * TRACE: The message body contains the...
  `

  console.log(description)
}

explain()

Lo que hice fue agregar dedente antes de la plantilla literal. ¿No lo crees?

$ bun index.ts
- 200 OK
  The request succeeded. The result meaning of "success" depends on the HTTP method:

  * GET: The resource has been fetched...
  * HEAD: The representation headers are...
  * PUT or POST: The resource describing...
  * TRACE: The message body contains the...

elimina toda la sangría innecesaria y la hace como esperábamos.

¿Por qué no probamos uno más complejo?

import dedent from 'dedent'

const explainStatus = (status: string) => {
    switch(status) {
        case '2xx':
          return dedent`
            - 200 OK
              The request succeeded. The result meaning of "success" depends on the HTTP method:

              * GET: The resource has been fetched and transmitted in the message body.
              * HEAD: The representation headers are included in the response without any message body.
              * PUT or POST: The resource describing the result of the action is transmitted in the message body.
              * TRACE: The message body contains the request message as received by the server.

            - 201 Created
              The request succeeded, and a new resource was created as a result.
              This is typically the response sent after POST requests, or some PUT requests.
            `

        case '4xx':
          return dedent`
            - 400 Bad Request
              The server cannot or will not process the request due to something that is perceived to be a client error
              (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).

            - 401 Unauthorized
              Although the HTTP standard specifies "unauthorized", semantically this response means "unauthenticated".
              That is, the client must authenticate itself to get the requested response.
          `

          default:
            return 'not yet!'
      }
}

console.log(explainStatus('2xx'))
$ bun index.ts
- 200 OK
  The request succeeded. The result meaning of "success" depends on the HTTP method:

  * GET: The resource has been fetched and transmitted in the message body.
  * HEAD: The representation headers are included in the response without any message body.
  * PUT or POST: The resource describing the result of the action is transmitted in the message body.
  * TRACE: The message body contains the request message as received by the server.

- 201 Created
  The request succeeded, and a new resource was created as a result.
  This is typically the response sent after POST requests, or some PUT requests.

Soo Smoooth!?

Declaración de liberación Este artículo se reproduce en: https://dev.to/javien/daily-package-dedent-1mi4?1 Si hay alguna infracción, comuníquese con [email protected] para eliminarlo.
Último tutorial Más>

Descargo de responsabilidad: Todos los recursos proporcionados provienen en parte de Internet. Si existe alguna infracción de sus derechos de autor u otros derechos e intereses, explique los motivos detallados y proporcione pruebas de los derechos de autor o derechos e intereses y luego envíelos al correo electrónico: [email protected]. Lo manejaremos por usted lo antes posible.

Copyright© 2022 湘ICP备2022001581号-3