vercel / ncc

Compile a Node.js project into a single file. Supports TypeScript, binary addons, dynamic requires.
https://npmjs.com/@vercel/ncc
MIT License
8.99k stars 285 forks source link

Does ncc support dynamic required(path) of fs.readdir ? #1190

Open seepine opened 1 month ago

seepine commented 1 month ago

Project Structure

- functions
  - user
    - info.ts
    - list.ts
  - health.ts
- util.ts
- index.ts

Use fs read functions dir and dynamic required all ts(health.ts)

util.ts

export function getFilesAndFoldersInDir(dir) {
  const basePath = path.join(process.cwd(), `${dir}`)
  const filesList = [];
  readFile(basePath, basePath, filesList);
  return filesList;
}
export function readFile(basePath, path, filesList) {
  const files = fs.readdirSync(path);
  files.forEach(walk);
  function walk(file) {
    const states = fs.statSync(path + "/" + file);
    if (states.isDirectory()) {
      readFile(basePath, path + "/" + file, filesList);
    } else {
      const obj: any = {};
      obj.size = states.size;
      obj.name = file;
      obj.path = path + "/" + file;
      obj.relativePath = obj.path.replace(basePath, "");
      obj.url = obj.relativePath.replace(".ts", "").replace(".js", "");
      filesList.push(obj);
    }
  }
}

index.ts

  let apiDir = "src/functions";
  let list = getFilesAndFoldersInDir(apiDir);
  list.forEach(async (obj: any) => {
    if (!obj.name.endsWith(".ts") && !obj.name.endsWith(".js")) {
      return
    }
    let handler = await import(obj.path);
    // TODO something...

  });