index.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { Rule, SchematicContext, Tree, SchematicsException } from '@angular-devkit/schematics';
  2. import { NodePackageInstallTask } from '@angular-devkit/schematics/tasks';
  3. const TSCONFIG_DATA = {
  4. include: ['src/**/*.ts'],
  5. exclude: ['src/**/*.spec.ts']
  6. };
  7. function safeReadJSON(path: string, tree: Tree) {
  8. try {
  9. return JSON.parse(tree.read(path)!.toString());
  10. } catch (e) {
  11. throw new SchematicsException(`Error when parsing ${path}: ${e.message}`);
  12. }
  13. }
  14. // Just return the tree
  15. export function ngAdd(): Rule {
  16. return (tree: Tree, context: SchematicContext) => {
  17. // Create tsconfig.doc.json file
  18. const tsconfigDocFile = 'tsconfig.doc.json';
  19. if (!tree.exists(tsconfigDocFile)) {
  20. tree.create(tsconfigDocFile, JSON.stringify(TSCONFIG_DATA));
  21. }
  22. // update package.json scripts
  23. const packageJsonFile = 'package.json';
  24. const packageJson = tree.exists(packageJsonFile) && safeReadJSON(packageJsonFile, tree);
  25. if (packageJson === undefined) {
  26. throw new SchematicsException('Could not locate package.json');
  27. }
  28. let packageScripts = {};
  29. if (packageJson['scripts']) {
  30. packageScripts = packageJson['scripts'];
  31. } else {
  32. packageScripts = {};
  33. }
  34. if (packageScripts) {
  35. packageScripts['compodoc:build'] = 'compodoc -p tsconfig.doc.json';
  36. packageScripts['compodoc:build-and-serve'] = 'compodoc -p tsconfig.doc.json -s';
  37. packageScripts['compodoc:serve'] = 'compodoc -s';
  38. }
  39. if (tree.exists(packageJsonFile)) {
  40. tree.overwrite(packageJsonFile, JSON.stringify(packageJson, null, 2));
  41. } else {
  42. tree.create(packageJsonFile, JSON.stringify(packageJson, null, 2));
  43. }
  44. // install package with npm
  45. context.addTask(new NodePackageInstallTask());
  46. return tree;
  47. };
  48. }