materialFileIcon
Material File Icon 主题图标解析
图标名称:
typescript图标 URL:
/material-icons/typescript.svg快速示例:
前置依赖
数据文件
需要导入 Material File Icon 映射数据:
typescript
import maps from 'zcw-shared/assets/materialFileIconMaps.json'数据文件包含:
- 默认文件和目录图标
- 扩展名到图标的映射(700+ 种扩展名)
- 特殊文件名到图标的映射
- 特殊目录名到图标的映射
图标资源
需要在项目中提供 SVG 图标资源,路径结构:
public/material-icons/
├── file.svg
├── folder.svg
├── typescript.svg
├── javascript.svg
├── vue.svg
└── ...图标可以从 vscode-material-icon-theme 获取。
函数签名
typescript
interface MaterialFileIconMaps {
defaultFileIcon: string
defaultFolderIcon: string
extToIcon: Record<string, string>
fileNameToIcon: Record<string, string>
folderNameToIcon: Record<string, string>
}
function materialIconNameForPath(
maps: MaterialFileIconMaps,
relPosixPath: string,
isDirectory: boolean,
): string
function materialFileIconUrl(
iconName: string,
baseUrl?: string
): string
function getFileIconUrl(
maps: MaterialFileIconMaps,
relPosixPath: string,
isDirectory: boolean,
baseUrl?: string,
): string参数
materialIconNameForPath
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
maps | MaterialFileIconMaps | 是 | 图标映射数据 |
relPosixPath | string | 是 | 相对路径(支持 / 和 \) |
isDirectory | boolean | 是 | 是否为目录 |
materialFileIconUrl
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
iconName | string | 是 | 图标名称 |
baseUrl | string | 否 | 基础 URL,默认为 '/' |
返回值
| 类型 | 说明 |
|---|---|
string | 图标名称或完整 URL |
使用示例
基本用法
typescript
import maps from 'zcw-shared/assets/materialFileIconMaps.json'
import { materialIconNameForPath } from 'zcw-shared/functions/file/materialFileIcon'
// TypeScript 文件
materialIconNameForPath(maps, 'src/main.ts', false)
// 'typescript'
// package.json(特殊文件名匹配)
materialIconNameForPath(maps, 'package.json', false)
// 'npm'
// Vue 组件
materialIconNameForPath(maps, 'App.vue', false)
// 'vue'
// 组件目录
materialIconNameForPath(maps, 'src/components', true)
// 'folder-components'生成图标 URL
typescript
import { materialFileIconUrl, getFileIconUrl } from 'zcw-shared/functions/file/materialFileIcon'
// 生成图标 URL
materialFileIconUrl('typescript', '/')
// '/material-icons/typescript.svg'
// 一键获取文件图标 URL
getFileIconUrl(maps, 'src/main.ts', false, '/')
// '/material-icons/typescript.svg'在 Vue 组件中使用
vue
<template>
<img :src="iconUrl" :alt="filename" />
</template>
<script setup lang="ts">
import maps from 'zcw-shared/assets/materialFileIconMaps.json'
import { getFileIconUrl } from 'zcw-shared/functions/file/materialFileIcon'
const props = defineProps<{
filename: string
isDirectory: boolean
}>()
const iconUrl = computed(() =>
getFileIconUrl(maps, props.filename, props.isDirectory, import.meta.env.BASE_URL)
)
</script>匹配规则
- 目录匹配:优先匹配
folderNameToIcon中的目录名(不区分大小写) - 特殊文件名匹配:优先匹配
fileNameToIcon中的完整文件名 - 扩展名匹配:从后向前匹配扩展名,支持复合扩展名(如
.d.ts) - 默认图标:无匹配时使用默认图标