vite import.meta.glob

396 阅读1分钟

最近在写一个小功能 查看文件源代码 因为用的是vite搭建项目,所以使用vite提供的api来实现

基本实现

const getRaw = (codePath: string) => {
  const allFiles = import.meta.glob(['@/**/*.{js,ts,vue,tsx,jsx,css,less,scss,}', '!@/@types/**'], {
    eager: true,
    as: 'raw',
  })
  console.log(`allFiles ==>`, allFiles)
  return allFiles[codePath]
}

@ 能生效是因为在vite.config.ts 中设置了别名

...
 resolve: {
      // 设置文件目录别名
      alias: {
        '@': resolve(__dirname, './src'),
      },
    },
    ....

image.png

这样在浏览器中打印就能拿到所有的文件的纯文本

组件

<template>
  <el-dialog :modelValue="show" title="Tips" width="900" :before-close="cancel">
    <section>
      <Code :html="getRaw(codePath)" />
    </section>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import Code from '@/components/code/index.vue'
type IProps = {
  show: boolean
  codePath: string
}
defineProps<IProps>()
const getRaw = (codePath: string) => {
  const allFiles = import.meta.glob(['@/**/*.{js,ts,vue,tsx,jsx,css,less,scss,}', '!@/@types/**'], {
    eager: true,
    as: 'raw',
  })
  return allFiles[codePath]
}
const emit = defineEmits(['update:show'])

const cancel = () => {
  emit('update:show', false)
}
</script>
<style lang="scss" scoped></style>

使用 (传入文件对应的路径就行)

<template>
  <main class="w-full h-full overflow-auto no-scroll">
    <SourceCode v-model:show="sourceCode.show" :codePath="sourceCode.codePath" />
    <header class="z-10 bg-gray-300 mb-5 p-4 text-xl font-bold sticky top-0">
      directives(指令) 代码地址==>
      <span class="text-gray-500">'@/directives/module'</span>
    </header>
    <!-- resize -->
    <section>
      <header
        @click="
          () => {
            sourceCode.show = true
            sourceCode.codePath = '/src/directives/module/resize.ts'
          }
        ">
        resize 代码地址==> '@/directives/module/resize'
      </header>
      <div class="p-4 bg-gray-50 mt-3 border border-dashed border-gray-400/40 rounded" v-resize="handleResize">
        resize (改变浏览器大小可触发)
      </div>
      <div class="p-4 bg-gray-50 mt-3 border border-dashed border-gray-400/40 rounded">{{ resizeInfo }}</div>
    </section>


  </main>
</template>
<script lang="ts" setup>
import SourceCode from '@/components/sourceCode/index.vue'

</script>
<style lang="scss" scoped>
section {
  @apply p-5 bg-gray-100 mx-5 mb-5 rounded-md border;
}
</style>

预览

image.png

这样就不用引入某个文件 如:

import SourceCode from '@/components/sourceCode/index.vue?raw通过 ?raw来实现了

遇到的问题

  1. 开发没问题,打包有问题
  2. 对api不够了解,不知道怎么排除不想引入的文件
  3. 不能动态引入,import.meta.glob不能使用变量

想法

1.修改代码并不断测试,找到问题原因引入的文件有问题 (在我的这个项目中引入了 .d.ts 声明文件,排除之后就不报错了)

2.排除不想引入的文件 ['@/**/*.{js,ts,vue,tsx,jsx,css,less,scss,}', '!@/@types/**'],数组形式,排除不想引入的文件、文件夹,具体写法自行搜索

3.api设计原因,防止生产报错,预防开发没问题,打包有问题