Skip to content

fileIcon

文件图标主题解析(当前资源:Catppuccin Icons)

图标名称:typescript
图标 URL:/file-icons/typescript.svg
typescript
快速示例:

前置依赖

数据文件

需要导入文件图标映射数据:

typescript
import maps from '@zengchaowu/shared/assets/fileIconMaps.json'

数据文件包含:

  • 默认文件和目录图标
  • 扩展名到图标的映射(700+ 种扩展名)
  • 特殊文件名到图标的映射
  • 特殊目录名到图标的映射

图标资源

需要在项目中提供 SVG 图标资源,路径结构:

public/file-icons/
  ├── _file.svg
  ├── _folder.svg
  ├── typescript.svg
  ├── javascript.svg
  ├── vue.svg
  └── ...

图标来自 catppuccin/vscode-icons(默认 mocha;pnpm run sync:file-icons 可刷新)。

函数签名

typescript
interface FileIconMaps {
  defaultFileIcon: string
  defaultFolderIcon: string
  extToIcon: Record<string, string>
  fileNameToIcon: Record<string, string>
  folderNameToIcon: Record<string, string>
}

function fileIconNameForPath(
  maps: FileIconMaps,
  relPosixPath: string,
  isDirectory: boolean,
): string

function fileIconUrl(
  iconName: string,
  baseUrl?: string
): string

function getFileIconUrl(
  maps: FileIconMaps,
  relPosixPath: string,
  isDirectory: boolean,
  baseUrl?: string,
): string

参数

fileIconNameForPath

参数名类型必填说明
mapsFileIconMaps图标映射数据
relPosixPathstring相对路径(支持 /\
isDirectoryboolean是否为目录

fileIconUrl

参数名类型必填说明
iconNamestring图标名称
baseUrlstring基础 URL,默认为 '/'

返回值

类型说明
string图标名称或完整 URL

使用示例

基本用法

typescript
import maps from '@zengchaowu/shared/assets/fileIconMaps.json'
import { fileIconNameForPath } from '@zengchaowu/shared/functions/file/fileIcon'

// TypeScript 文件
fileIconNameForPath(maps, 'src/main.ts', false)
// 'typescript'

// package.json(特殊文件名匹配)
fileIconNameForPath(maps, 'package.json', false)
// 'package-json'

// Vue 组件
fileIconNameForPath(maps, 'App.vue', false)
// 'vue'

// 组件目录
fileIconNameForPath(maps, 'src/components', true)
// 'folder_components'

生成图标 URL

typescript
import { fileIconUrl, getFileIconUrl } from '@zengchaowu/shared/functions/file/fileIcon'

// 生成图标 URL
fileIconUrl('typescript', '/')
// '/file-icons/typescript.svg'

// 一键获取文件图标 URL
getFileIconUrl(maps, 'src/main.ts', false, '/')
// '/file-icons/typescript.svg'

在 Vue 组件中使用

vue
<template>
  <img :src="iconUrl" :alt="filename" />
</template>

<script setup lang="ts">
import maps from '@zengchaowu/shared/assets/fileIconMaps.json'
import { getFileIconUrl } from '@zengchaowu/shared/functions/file/fileIcon'

const props = defineProps<{
  filename: string
  isDirectory: boolean
}>()

const iconUrl = computed(() =>
  getFileIconUrl(maps, props.filename, props.isDirectory, import.meta.env.BASE_URL)
)
</script>

匹配规则

  1. 目录匹配:优先匹配 folderNameToIcon 中的目录名(不区分大小写)
  2. 特殊文件名匹配:优先匹配 fileNameToIcon 中的完整文件名
  3. 扩展名匹配:从后向前匹配扩展名,支持复合扩展名(如 .d.ts
  4. 默认图标:无匹配时使用默认图标