能否收集满足条件的文件夹名称做ts类型?

我现在有一个文件夹

- root
  - folder1
    - index.vue
  - folder2
    - index.vue
    - subfolder
      - index.vue
  - folder3
    - index.vue
    - subfolder1
      - index.vue
      - anotherfolder
        - index.vue

能否收集这个文件夹下 所有子级包含index.vue文件的文件夹名称,以此作为一个类型?
root的内容是动态的。
我希望的:

type PopupsItem = 'folder1'|'folder2'|'folder3'|'subfolder'|'subfolder1'|'anotherfolder';
阅读 345
1 个回答

需要用node去读文件夹与文件属性:

const fs = require('fs');
const path = require('path');

function getDirectoriesWithIndexVue(directory) {
  let result = [];

  const files = fs.readdirSync(directory, { withFileTypes: true });
  for (const file of files) {
    if (file.isDirectory()) {
      const subDir = path.join(directory, file.name);
      const indexPath = path.join(subDir, 'index.vue');
      if (fs.existsSync(indexPath)) {
        result.push(file.name);
      }
      result = result.concat(getDirectoriesWithIndexVue(subDir));
    }
  }

  return result;
}

// 与 root 文件夹同级的下执行, 进入 root
const rootDirectory = './src';
const items = getDirectoriesWithIndexVue(rootDirectory);
console.log(items); // 输出包含 index.vue 文件的子文件夹名称

输出:
image.png

logo
Microsoft
子站问答
访问
宣传栏