Managing the types folder with a simple script

Yeom suyun - Nov 19 '23 - - Dev Community

A few weeks ago, I wrote an article on setting up a project for an npm package using JSDoc.


When using JSDoc, it generates d.ts files using tsc.
However, if there are deleted js files during this process, the corresponding d.ts files are not automatically removed.
If I delete the types folder before running tsc, this issue can be resolved.
However, when working with VSCode, it can be quite annoying that unchanged files are marked as modified in the Git tab.
To address this problem, I've written a simple script.
import {
  readdirSync,
  rmdirSync,
  statSync,
  unlinkSync
} from "node:fs"

import { exec } from "node:child_process"
import { fileURLToPath } from "node:url"
import path from "node:path"

const dir = fileURLToPath(new URL("..", import.meta.url))
const pacakge_path = `${dir}/packages/${process.argv[2]}`
const current_time = Date.now()

exec(
  `cd ${pacakge_path} && tsc`,
  () => {
    /**
     * @param {string} dir_path
     * @returns {void}
     */
    function clean_dir(dir_path) {
      const files = readdirSync(dir_path)
      let length = files.length
      for (const file of files) {
        const file_path = path.join(dir_path, file)
        const stat = statSync(file_path)
        if (stat.isDirectory()) clean_dir(file_path)
        else {
          const modified_time = new Date(stat.mtime).getTime()
          if (modified_time < current_time) {
            unlinkSync(file_path)
            length--
          }
        }
      }
      if (!length) rmdirSync(dir_path)
    }
    clean_dir(pacakge_path + "/types")
  }
)
Enter fullscreen mode Exit fullscreen mode

The principle is simple.
Record the current time in JavaScript, run tsc, and then delete the unchanged files.
If you're curious about the entire project, check out the StackBlitz link below.

Thank you.

https://stackblitz.com/edit/github-p9xwsc?file=scripts%2Ftsc_with_clean.js

. . . . . . . . . . . . . . . . .
Terabox Video Player