вы когда-нибудь пытались написать многострочный абзац в буквальном шаблоне, но осознавали, что он сохраняет отступление, которое в конечном итоге использовало добавление строки с \ 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...]
]]подождите, мне нужно удалить отступления?
]
] Нах. Я не могу отказаться от своего прекрасно отформатированного кода.
]
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()]
]]я возьму это. ?
]
по этой причине, многослойный текст всегда для меня - головная боль.
], но теперь вам больше не нужно вести переговоры с самим собой. Просто используйте Dedent.
]
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()]
то, что я сделал, было добавлено до буквального шаблона. Ты не веришь в это?
]
$ 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...]
он удаляет все ненужные отступления и делает его таким, как мы ожидали.
Почему бы нам не попробовать более сложный?
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!?
] ] ]Отказ от ответственности: Все предоставленные ресурсы частично взяты из Интернета. В случае нарушения ваших авторских прав или других прав и интересов, пожалуйста, объясните подробные причины и предоставьте доказательства авторских прав или прав и интересов, а затем отправьте их по электронной почте: [email protected]. Мы сделаем это за вас как можно скорее.
Copyright© 2022 湘ICP备2022001581号-3