type-check.mjs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import fs from "fs"
  2. import { glob } from "glob"
  3. import path from "path"
  4. import ts from "typescript"
  5. import vueTsc from "vue-tsc"
  6. import { fileURLToPath } from "url"
  7. /**
  8. * Helper function to find files to perform type check on
  9. */
  10. const findFilesToPerformTypeCheck = (directoryPaths, filePatterns) => {
  11. const files = []
  12. directoryPaths.forEach((directoryPath) => {
  13. if (!fs.existsSync(directoryPath)) {
  14. console.error(`Directory not found: ${directoryPath}`)
  15. process.exit(1)
  16. }
  17. files.push(
  18. ...glob.sync(filePatterns, {
  19. cwd: directoryPath,
  20. ignore: ["**/__tests__/**", "**/*.d.ts"],
  21. absolute: true,
  22. })
  23. )
  24. })
  25. return files
  26. }
  27. // Derive the current file's directory path `__dirname` from the URL of this module `__filename`
  28. const __filename = fileURLToPath(import.meta.url)
  29. const __dirname = path.dirname(__filename)
  30. // Define the directory paths and file patterns to perform type checks on
  31. const directoryPaths = [path.resolve(__dirname, "src", "services")]
  32. const filePatterns = ["**/*.ts"]
  33. const tsConfigFileName = path.resolve(__dirname, "tsconfig.json")
  34. const tsConfig = ts.readConfigFile(tsConfigFileName, ts.sys.readFile)
  35. const { options } = ts.parseJsonConfigFileContent(
  36. tsConfig.config,
  37. ts.sys,
  38. __dirname
  39. )
  40. const files = findFilesToPerformTypeCheck(directoryPaths, filePatterns)
  41. const host = ts.createCompilerHost(options)
  42. const program = vueTsc.createProgram({
  43. rootNames: files,
  44. options: { ...options, noEmit: true },
  45. host,
  46. })
  47. // Perform type checking
  48. const diagnostics = ts
  49. .getPreEmitDiagnostics(program)
  50. // Filter diagnostics to include only errors from files in the specified directory
  51. .filter(({ file }) => {
  52. if (!file) {
  53. return false
  54. }
  55. return directoryPaths.some((directoryPath) =>
  56. path.resolve(file.fileName).includes(directoryPath)
  57. )
  58. })
  59. if (!diagnostics.length) {
  60. console.log("Type checking passed.")
  61. // Success
  62. process.exit(0)
  63. }
  64. console.log("TypeScript diagnostics:")
  65. const formatHost = {
  66. getCanonicalFileName: (fileName) => fileName,
  67. getCurrentDirectory: host.getCurrentDirectory,
  68. getNewLine: () => ts.sys.newLine,
  69. }
  70. const formattedDiagnostics = ts.formatDiagnosticsWithColorAndContext(
  71. diagnostics,
  72. formatHost
  73. )
  74. console.error(formattedDiagnostics)
  75. // Failure
  76. process.exit(1)