首页 > web前端 > js教程 > 正文

Shadcn CLI如何使用错误常量来提高代码可读性

碧海醫心
发布: 2024-10-15 08:12:09
转载
654人浏览过

在本文中,我们分析了如何在 shadcn/ui 代码库中使用名为 error.ts 的文件。

Shadcn CLI如何使用错误常量来提高代码可读性

utils/errors.ts

error.ts 包含 12 个变量:

export const missing_dir_or_empty_project = "1"
export const existing_config = "2"
export const missing_config = "3"
export const failed_config_read = "4"
export const tailwind_not_configured = "5"
export const import_alias_missing = "6"
export const unsupported_framework = "7"
export const component_url_not_found = "8"
export const component_url_unauthorized = "9"
export const component_url_forbidden = "10"
export const component_url_bad_request = "11"
export const component_url_internal_server_error = "12"
登录后复制

这些是描述性的,解释了正在处理的错误类型,例如,missing_dir_or_empty_project 可能用于缺少目录或空项目的场景。

这些变量值有什么特殊含义吗?它们只是分配为字符串的数字。一旦我们了解了如何使用这些变量,它就更有意义了。

preflight-init.ts 中的用法:

如果你打开这个 preflight-init.ts,你会发现下面的代码片段。

// ensure target directory exists.
 // check for empty project. we assume if no package.json exists, the project is empty.
 if (
   !fs.existssync(options.cwd) ||
   !fs.existssync(path.resolve(options.cwd, "package.json"))
 ) {
   errors[errors.missing_dir_or_empty_project] = true
   return {
     errors,
     projectinfo: null,
   }
 }
登录后复制

注意这个errors[errors.missing_dir_or_empty_project]=true,这里的errors是一个对象。 missing_dir_or_empty_project 的值是多少?如前所述,它是“1”。

这意味着错误对象如下所示:

{
 "1": true
}
登录后复制

这很好,但是这个错误对象是如何使用的以及在哪里使用?答案就在 init.ts 中。

init.ts 中的错误对象

在 init.ts 的第 91 行,你会发现下面的 if 块。

if (preflight.errors[ERRORS.MISSING_DIR_OR_EMPTY_PROJECT]) {

 const { projectPath } = await createProject(options)

 if (!projectPath) {
   process.exit(1)
 }

  options.cwd = projectPath
 options.isNewProject = true
}
登录后复制

如果这个检查类似于 preflight.error[“1”],你的下一个想法就是这个神秘的值是什么。这意味着,error.ts 中的这些常量用于提高代码可读性

关于我们:

在 think throo,我们的使命是教授开源项目中使用的高级代码库架构概念。

通过在 next.js/react 中练习高级架构概念,将您的编码技能提高 10 倍,学习最佳实践并构建生产级项目。

我们是开源的 — https://github.com/thinkthroo/thinkthroo (请给我们一颗星!)

我们还提供网络开发和技术写作服务。请通过hello@thinkthroo.com联系我们了解更多信息!

参考文献:

  1. https://github.com/shadcn-ui/ui/blob/main/packages/shadcn/src/preflights/preflight-init.ts#l22

  2. https://github.com/shadcn-ui/ui/blob/main/packages/shadcn/src/utils/errors.ts

  3. https://github.com/search?q=repo%3ashadcn-ui%2fui%20errors&type=code

  4. https://github.com/shadcn-ui/ui/blob/1297abc8820480681ccec1bb026b29b30d9c858d/packages/shadcn/src/commands/init.ts#l91

以上就是Shadcn CLI如何使用错误常量来提高代码可读性的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:dev.to网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号