generate-ts.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { resolve } from "path";
  2. import { writeFileSync, unlinkSync, rmSync } from "fs";
  3. import { execSync } from "child_process";
  4. import dts from "rollup-plugin-dts";
  5. import tsResolve from "@rollup/plugin-node-resolve";
  6. import * as Rollup from "rollup";
  7. const generateTs = (app: string) => {
  8. const enter = app ? `src/app/${app}/` : `src/board/`;
  9. const enterPath = resolve(__dirname, enter, `index.ts`);
  10. const tsconfigPath = resolve(__dirname, "./tsconfig.prod.json");
  11. const outPath = resolve(__dirname, "dist/tempts");
  12. const tsconfig = {
  13. compilerOptions: {
  14. target: "es2015",
  15. useDefineForClassFields: true,
  16. module: "ESNext",
  17. lib: ["es2015", "DOM", "DOM.Iterable"],
  18. skipLibCheck: true,
  19. /* Bundler mode */
  20. moduleResolution: "Node",
  21. resolveJsonModule: true,
  22. isolatedModules: true,
  23. jsx: "preserve",
  24. /* Linting */
  25. noUnusedLocals: true,
  26. noUnusedParameters: true,
  27. noFallthroughCasesInSwitch: true,
  28. allowImportingTsExtensions: true,
  29. emitDeclarationOnly: true, // 只输出声明文件(ts 产物)
  30. declaration: true, // 自动生成声明文件
  31. declarationDir: outPath, // 声明文件生成的目录
  32. incremental: false, // 启用增量编译
  33. },
  34. include: [enterPath, "src/vite-env.d.ts"],
  35. references: [
  36. {
  37. path: "./tsconfig.node.json",
  38. },
  39. ],
  40. };
  41. writeFileSync(tsconfigPath, JSON.stringify(tsconfig, null, 2));
  42. try {
  43. execSync(`cd ${__dirname} && npm run tsc`, { stdio: "inherit" });
  44. unlinkSync(tsconfigPath);
  45. } catch (error) {
  46. console.error("Error executing command:", error);
  47. throw error;
  48. }
  49. return outPath;
  50. };
  51. const mergeTs = async (app: string, input: string) => {
  52. const name = app ? app : "board";
  53. const enter = resolve(input, `${app ? `app/${app}/` : ``}index.d.ts`);
  54. const out = resolve(__dirname, `./dist/${name}.d.ts`);
  55. const bundle = await Rollup.rollup({
  56. input: enter,
  57. plugins: [dts(), tsResolve()],
  58. });
  59. await bundle.write({ file: out, format: "es" });
  60. rmSync(input, { recursive: true, force: true });
  61. };
  62. export const generateDTS = async (app: string) => {
  63. await mergeTs(app, generateTs(app));
  64. };