别名
别名是一种为导入创建快捷方式的方法。
¥An alias is a way to create shortcuts for your imports.
别名可以帮助改善具有许多目录或相对导入的代码库的开发体验。
¥Aliases can help improve the development experience in codebases with many directories or relative imports.
---import Button from '../../components/controls/Button.astro';import logoUrl from '../../assets/logo.png?url';---在此示例中,开发者需要了解 src/pages/about/company.astro、src/components/controls/Button.astro 和 src/assets/logo.png 之间的树关系。然后,如果要移动 company.astro 文件,这些导入也需要更新。
¥In this example, a developer would need to understand the tree relationship between src/pages/about/company.astro, src/components/controls/Button.astro, and src/assets/logo.png. And then, if the company.astro file were to be moved, these imports would also need to be updated.
你可以从 tsconfig.json 或 jsconfig.json 添加导入别名。
¥You can add import aliases from either tsconfig.json or jsconfig.json.
{ "compilerOptions": { "baseUrl": ".", "paths": { "@components/*": ["src/components/*"], "@assets/*": ["src/assets/*"] } }}更改此配置后,开发服务器将自动重新启动。你现在可以在项目的任何位置使用别名进行导入:
¥The development server will automatically restart after this configuration change. You can now import using the aliases anywhere in your project:
---import Button from '@components/controls/Button.astro';import logoUrl from '@assets/logo.png?url';---这些别名也会自动集成到 VS Code 和其他编辑器中。
¥These aliases are also integrated automatically into VS Code and other editors.
Learn