@angular-devkit/schematics#chain TypeScript Examples

The following examples show how to use @angular-devkit/schematics#chain. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.ts    From ng-ant-admin with MIT License 6 votes vote down vote up
export default function (_options: any): Rule {
    return (tree: Tree, _context: SchematicContext) => {
        return chain([
            async () => {
                let path = "";
                // 是一级菜单
                if (_options.mName === _options.name) {
                    path = `src/app/pages/${dasherize(_options.mName)}/${dasherize(_options.mName)}-routing.module.ts`;
                } else {
                    path = `src/app/pages/${dasherize(_options.mName)}/${dasherize(_options.name)}/${dasherize(_options.name)}-routing.module.ts`;

                }
                // 读取文件
                let tsFile = tree.read(path)?.toString()!;
                // 转换成抽象语法树
                // let ast = ts.createSourceFile('default-routing.module', tsFile, ScriptTarget.Latest)
                let selector = createCssSelectorForTs(tsFile)
                let result = selector.queryOne(`SourceFile VariableStatement VariableDeclarationList VariableDeclaration ArrayLiteralExpression ObjectLiteralExpression
`) as (ts.ObjectLiteralExpression);
                let recorder = tree.beginUpdate(path);
                recorder.remove(result.pos,result.end-result.pos);
                recorder.insertRight(result.pos, `
  {path: '', component: ${classify(_options.name)}Component, data: {title: '${_options.title}', key: '${dasherize(_options.name)}'}}`);
                await tree.commitUpdate(recorder);
            }
        ]);
    };
}
Example #2
Source File: merge-source.rule.ts    From angular-miniprogram with MIT License 6 votes vote down vote up
export function mergeSourceRuleFactory(options: FormsHookOptions) {
  return (tree: Tree) => {
    const localSourceMap = new Map<string, Buffer>();
    for (let i = 0; i < SCHEMATICS_FORMS_LIBRARY_HOOK_FILE_LIST.length; i++) {
      const filePath = SCHEMATICS_FORMS_LIBRARY_HOOK_FILE_LIST[i];
      if (tree.exists(filePath)) {
        localSourceMap.set(filePath, tree.read(filePath));
      }
    }
    const angularFormsSource = apply(
      url(path.relative(options.schematicPath, ANGULAR_FORMS_PATH)),
      [
        filter((path) => {
          return path.endsWith('.ts') && !path.startsWith('/test');
        }),
        filter((path) => {
          return !path.endsWith('.spec.ts');
        }),
        move(SCHEMATICS_FORMS_LIBRARY_PATH),
      ]
    );
    return chain([
      mergeWith(angularFormsSource, MergeStrategy.Overwrite),
      (tree) => {
        localSourceMap.forEach((content, filePath) => {
          tree.overwrite(filePath, content);
        });
      },
    ]);
  };
}
Example #3
Source File: index.ts    From angular-miniprogram with MIT License 6 votes vote down vote up
export default function (options: FormsHookOptions) {
  options.schematicPath = __dirname;
  return (tree: Tree, context: SchematicContext) => {
    return chain([
      getAngularSubDirRuleFactory(options),
      mergeSourceRuleFactory(options),
    ]);
  };
}
Example #4
Source File: merge-source.rule.ts    From angular-miniprogram with MIT License 6 votes vote down vote up
export function mergeSourceRuleFactory(options: FormsHookOptions) {
  return (tree: Tree) => {
    const angularFormsSource = apply(
      url(path.relative(options.schematicPath, ANGULAR_COMMON_PATH)),
      [
        // todo 过滤掉所有i18n文件
        filter((path) => {
          return path.endsWith('.ts') && !path.startsWith('/test');
        }),
        filter((path) => {
          return !path.endsWith('.spec.ts');
        }),
        // filter((path) => {
        //   return !path.includes('i18n/');
        // }),
        // filter((path) => {
        //   return !filterFileList.some((item) => path.includes(item));
        // }),
        move(SCHEMATICS_COMMON_LIBRARY_PATH),
      ]
    );
    return chain([mergeWith(angularFormsSource, MergeStrategy.Overwrite)]);
  };
}
Example #5
Source File: index.ts    From angular-miniprogram with MIT License 6 votes vote down vote up
export default function (options: CommonHookOptions) {
  options.schematicPath = __dirname;
  return (tree: Tree, context: SchematicContext) => {
    return chain([
      getAngularSubDirRuleFactory(options),
      mergeSourceRuleFactory(options),
      changeStructuralDirectiveRuleFactory(options),
      removeNgComponentOutletRuleFactory(),
      removeI18nRuleFactory(),
      forEach((entry) => {
        if (
          entry.path.startsWith('/src/library/common') &&
          entry.path.endsWith('.ts')
        ) {
          return {
            content: Buffer.from(
              entry.content
                .toString()
                .replace(/@angular\/common/g, `angular-miniprogram/common`)
            ),
            path: entry.path,
          };
        }
        return entry;
      }),
    ]);
  };
}
Example #6
Source File: index.ts    From angular-git-info with MIT License 6 votes vote down vote up
export function gitInfo(): Rule {
    return (tree: Tree, context: SchematicContext) => {
        return chain([
            updateDependencies(),
            addVersionGeneratorFile(),
            addVersionGeneratorToGitignore(),
            addScriptsToPackageJson(),
        ])(tree, context);
    };
}
Example #7
Source File: index.ts    From edit-in-place with MIT License 6 votes vote down vote up
export default function(options: SchemaOptions): Rule {
  return (host: Tree, context: SchematicContext) => {
    const project = getProject(host, options.project);
    const sourceRoot = (project && project.sourceRoot) || 'src';
    options.module = findRootModule(host, options.module, sourceRoot) as string;

    return chain([
      addImportsToModuleFile(options, ['EditableModule']),
      addImportsToModuleDeclaration(options, ['EditableModule'])
    ])(host, context);
  };
}
Example #8
Source File: index.ts    From ng-ant-admin with MIT License 6 votes vote down vote up
fnGenerateModalModule = function (tree: Tree, path: string, name: string): Rule {
    return chain([
        async () => {
            // 读取文件
            let tsFile = tree.read(path)?.toString()!;
            // 转换成抽象语法树
            // let ast = ts.createSourceFile('default-routing.module', tsFile, ScriptTarget.Latest)
            let selector = createCssSelectorForTs(tsFile)
            let result = selector.queryOne(`SourceFile ClassDeclaration Decorator CallExpression ObjectLiteralExpression PropertyAssignment[name=imports] ArrayLiteralExpression Identifier`) as (ts.Identifier);
            let recorder = tree.beginUpdate(path);
            recorder.insertLeft(result.pos, `
    ${classify(name)}ModalModule,`);
            await tree.commitUpdate(recorder);
        }
    ]);
}
Example #9
Source File: index.ts    From ng-ant-admin with MIT License 6 votes vote down vote up
fnGenerateRouteModulePath = function (tree: Tree, path: string, name: string): Rule {
    return chain([
        async () => {
            // 读取文件
            let tsFile = tree.read(path)?.toString()!;
            // 转换成抽象语法树
            // let ast = ts.createSourceFile('default-routing.module', tsFile, ScriptTarget.Latest)
            let selector = createCssSelectorForTs(tsFile)
            let result = selector.queryOne(`SourceFile VariableStatement VariableDeclaration ArrayLiteralExpression ObjectLiteralExpression`) as (ts.ObjectLiteralExpression);
            let recorder = tree.beginUpdate(path);
            recorder.insertLeft(result.pos, `
  {path: '${dasherize(name)}', loadChildren: () => import('./${dasherize(name)}/${dasherize(name)}.module').then(m => m.${classify(name)}Module)},`);
            await tree.commitUpdate(recorder);
        }
    ]);
}
Example #10
Source File: index.ts    From ng-ant-admin with MIT License 6 votes vote down vote up
fnGenerateImport = function (name: string, filePath: string, tree: Tree, suffix: 'Component' | 'Modal' = 'Component', isOneLevel = true, mName = ''): Rule {
    return chain([
        async () => {
            let path = filePath;
            // 读取文件
            let tsFile = tree.read(path)?.toString()!;
            // 转换成抽象语法树
            // let ast = ts.createSourceFile('default-routing.module', tsFile, ScriptTarget.Latest)
            let selector = createCssSelectorForTs(tsFile)
            let result = selector.queryOne(`SourceFile`) as (ts.SourceFile);
            let recorder = tree.beginUpdate(path);
            // recorder.remove(result.pos, result.end - result.pos);
            console.log(suffix);
            if (suffix === "Component") {
                recorder.insertLeft(result.pos, `import {${classify(name)}Component} from "./${dasherize(name)}.component";
`);
            } else {
                let path = `import {${classify(name)}ModalModule} from "@widget/biz-widget/${dasherize(name)}-modal/${dasherize(name)}-modal.module";
`;
                if (!isOneLevel) {
                    path = `import {${classify(name)}ModalModule} from "@widget/biz-widget/${dasherize(mName)}/${dasherize(name)}-modal/${dasherize(name)}-modal.module";
`;
                }
                recorder.insertLeft(result.pos, path);
            }

            await tree.commitUpdate(recorder);
        }
    ]);
}
Example #11
Source File: index.ts    From ng-ant-admin with MIT License 6 votes vote down vote up
// 生成路由代码
export default function (_options: any): Rule {
  return (tree: Tree, _context: SchematicContext) => {
    return chain([
      async () => {
        // 读取文件
        let tsFile = tree.read('src/app/layout/default/default-routing.module.ts')?.toString()!;
        // 转换成抽象语法树
        // let ast = ts.createSourceFile('default-routing.module', tsFile, ScriptTarget.Latest)
        let selector = createCssSelectorForTs(tsFile)
        let result = selector.queryOne(`SourceFile VariableStatement VariableDeclarationList VariableDeclaration ArrayLiteralExpression ObjectLiteralExpression PropertyAssignment ArrayLiteralExpression ObjectLiteralExpression`) as (ts.ObjectLiteralExpression);
        let recorder = tree.beginUpdate('src/app/layout/default/default-routing.module.ts');
        recorder.insertLeft(result.pos, `
      {
        path: '${dasherize(_options.name)}',
        loadChildren: () => import('../../pages/${dasherize(_options.name)}/${dasherize(_options.name)}.module').then(m => m.${classify(_options.name)}Module)
      },`);
        await tree.commitUpdate(recorder);
      }
    ]);
  };
}
Example #12
Source File: index.ts    From ng-ant-admin with MIT License 6 votes vote down vote up
// 二级菜单时,修改一级模块路由
function generTwoLevelModuleRoute(_options: any, tree: Tree): Rule {
    return chain([
        async () => {
            let path = `src/app/pages/${dasherize(_options.name)}/${dasherize(_options.name)}-routing.module.ts`;
            // 读取文件
            let tsFile = tree.read(path)?.toString()!;
            // 转换成抽象语法树
            // let ast = ts.createSourceFile('default-routing.module', tsFile, ScriptTarget.Latest)
            let selector = createCssSelectorForTs(tsFile)
            let result = selector.queryOne(`SourceFile VariableStatement VariableDeclarationList VariableDeclaration ArrayLiteralExpression ObjectLiteralExpression
`) as (ts.ObjectLiteralExpression);
            let recorder = tree.beginUpdate(path);
            recorder.remove(result.pos, result.end - result.pos);
            recorder.insertRight(result.pos, `
  {path: 'demo', loadChildren: () => import('./demo/demo.module').then(m => m.DemoModule)},
  {path: '', redirectTo: 'demo', pathMatch: 'full'},`);
            await tree.commitUpdate(recorder);
        }
    ]);
}
Example #13
Source File: index.ts    From ng-ant-admin with MIT License 6 votes vote down vote up
export default function (_options: any): Rule {
    return (tree: Tree, _context: SchematicContext) => {
        /*是二级菜单*/
        if (_options.isTwoLevel == true) {
            return chain([
                schematic('layout-lazy-m', {name: _options.name}),
                schematic('b-m', {name: _options.name, isTwoLevel: false}),
                generTwoLevelModuleRoute(_options, tree),
                // schematic('component-lazy-m', {name: _options.name, isTwoLevel: false}),
            ]);
        } else {
            /*一级菜单*/
            return chain([
                /* 添加default-routing.module.ts 路由*/
                schematic('layout-lazy-m', {name: _options.name}),
                schematic('b-s', {dirname: _options.name, filename: _options.name}),
                schematic('b-m', {name: _options.name, isTwoLevel: false}),
                schematic('b-c', {name: _options.name, mName: _options.name}),
                fnGenerateImport(_options.name, `src/app/pages/${dasherize(_options.name)}/${dasherize(_options.name)}-routing.module.ts`, tree)
            ]);
        }
    };
}
Example #14
Source File: schematic.ts    From nx-plugins with MIT License 6 votes vote down vote up
export function updateProject(adapter: BaseAdapter): Rule {
  return async () => {
    return chain([
      updateWorkspace((workspace) => {
        const project = workspace.projects.get(adapter.options.project);
        project.targets.add({
          name: 'deploy',
          ...adapter.getDeployActionConfiguration(),
        });
        project.targets.add({
          name: 'destroy',
          ...adapter.getDestroyActionConfiguration(),
        });
      }),
      updateJsonInTree(
        join(adapter.project.root, 'tsconfig.app.json'),
        (json) => {
          const exclude: string[] = json.exclude;
          const excludePaths = 'infrastructure/**/*.ts';

          if (!exclude) {
            json.exclude = [excludePaths];
          } else {
            exclude.push(excludePaths);
          }
          return json;
        }
      ),
    ]);
  };
}
Example #15
Source File: index.ts    From ng-ant-admin with MIT License 6 votes vote down vote up
function twoLevelRule(_options: any): Rule {
    return (tree: Tree, _context: SchematicContext) => {
        let source = apply(url(`./files/src/app/pages`), [move(`./src/app/pages/${_options.mName}`), applyTemplates({
            ...strings,
            ..._options, // 使用者所輸入的參數
        })]);
        return chain([
            mergeWith(source),
            schematic('b-s', {dirname: _options.mName, filename: _options.name},),
            schematic('b-m', {name: _options.name, isTwoLevel: true},),
            move(`./src/app/pages/${_options.name}`, `./src/app/pages/${_options.mName}/${_options.name}`),
            schematic('component-lazy-m', {mName: _options.mName, name: _options.name},),
        ])
    };

}
Example #16
Source File: index.ts    From cli with Apache License 2.0 6 votes vote down vote up
export default function (options: CoveoSchema): Rule {
  return async (tree: Tree, _context: SchematicContext) => {
    const workspace = await getWorkspace(tree);
    const project = getProjectFromWorkspace(workspace, options.project);

    if (project.extensions.projectType === ProjectType.Application) {
      return chain([
        createServerDirectory(options),
        createFiles(options),
        installServerDependencies(options),
      ]);
    }
    return;
  };
}
Example #17
Source File: schematic.ts    From nx-plugins with MIT License 6 votes vote down vote up
function generateInfrastructureCode(adapter: BaseAdapter) {
  return (host: Tree, context: SchematicContext) => {
    const template = adapter.getApplicationTypeTemplate();
    if (!template) {
      throw new Error(`Can't find a supported build target for the project`);
    }
    const templateSource = apply(
      url(`./files/${adapter.getApplicationTemplatePath()}`),
      [template, move(join(adapter.project.root))]
    );

    const rule = chain([branchAndMerge(chain([mergeWith(templateSource)]))]);
    return rule(host, context);
  };
}
Example #18
Source File: index.ts    From cli with Apache License 2.0 6 votes vote down vote up
export default function (options: CoveoSchema): Rule {
  return async (tree: Tree) => {
    const workspace = await getWorkspace(tree);
    const project = getProjectFromWorkspace(workspace, options.project);

    return chain([
      addMaterialAngular(options),
      createFiles(options),
      updateNgModule(options, project),
      updateTsConfig(options),
    ]);
  };
}
Example #19
Source File: schematic.ts    From nx-plugins with MIT License 6 votes vote down vote up
function initializeCloudProviderApplication(adapter: BaseAdapter) {
  return chain([
    generateNewPulumiProject(adapter),
    mergePulumiProjectIntoTree(adapter),
    cleanupTempPulumiProject(adapter),
    generateInfrastructureCode(adapter),
    updateProject(adapter),
  ]);
}
Example #20
Source File: schematic.ts    From nx-plugins with MIT License 6 votes vote down vote up
export default function (options: NxDeployItInitSchematicSchema) {
  return async (host: Tree, context: SchematicContext): Promise<Rule> => {
    const workspace = await getWorkspace(host);
    const project = workspace.projects.get(options.project);

    if (!project) {
      context.logger.error(`Project doesn't exist`);
      return chain([]);
    }

    if (project.targets.has('deploy')) {
      context.logger.error(
        `Your project is already configured with a deploy job`
      );
      return chain([]);
    }

    if (host.exists(join(project.root, 'infrastructure', 'Pulumi.yaml'))) {
      context.logger.error(`This project already has an infrastructure`);
      return chain([]);
    }

    const adapter = getAdapter(project, options, host);
    await adapter.extendOptionsByUserInput();

    return chain([initializeCloudProviderApplication(adapter)]);
  };
}
Example #21
Source File: index.ts    From garment with MIT License 6 votes vote down vote up
export default function(options: Options): Rule {
  return () => {
    if (!options.getWorkspace) {
      throw new Error('getWorkspace option is missing');
      return;
    }
    const workspace = options.getWorkspace();

    const baseTsConfigPath = Path.join(workspace.cwd, 'tsconfig.base.json');

    return chain([syncTsConfigs(workspace, baseTsConfigPath, options.name)]);
  };
}
Example #22
Source File: index.ts    From garment with MIT License 6 votes vote down vote up
export default function(options: PackageSchematicOptions): Rule {
  return (_tree: Tree) => {
    let { projectName } = options;

    if (!projectName) {
      throw new SchematicsException('projectName option is required.');
    }

    const { projects } = readJson(_tree, 'garment.json');

    if (!projects[projectName]) {
      throw new SchematicsException(
        `Couldn't find project ${projectName} in garment.json`
      );
    }

    const packagePath = projects[projectName].path;

    let source = apply(url('../../templates/runner/__tests__'), [
      applyTemplates(
        {
          dot: '.',
          ...strings
        },
        { interpolationStart: '___', interpolationEnd: '___' }
      ),
      move(Path.join(packagePath, '__tests__'))
    ]);

    return chain([
      mergeWith(source),
      addPackageJsonDependencies(
        `${packagePath}/package.json`,
        'utils/fixture-helper/package.json'
      )
    ]);
  };
}
Example #23
Source File: index.ts    From garment with MIT License 6 votes vote down vote up
export default function(options: Options): Rule {
  return () => {
    if (!options.getWorkspace) {
      return;
    }
    const { field, value, projects, merge } = options;
    if (!field) {
      throw new Error('Provide field name');
    }
    if (!value) {
      throw new Error('Provide value');
    }
    const workspace = options.getWorkspace();
    const projectNames = projects.split(',').map(_ => _.trim());

    return chain([
      syncPackageJson(workspace, field, value, projectNames, Boolean(merge))
    ]);
  };
}
Example #24
Source File: index.ts    From garment with MIT License 6 votes vote down vote up
export default function(options: Options): Rule {
  return () => {
    if (!options.getWorkspace) {
      return;
    }
    const { project, dep, dev = false } = options;
    if (!project) {
      throw new Error('Provide project name');
    }
    if (!dep) {
      throw new Error('Provide dependency name');
    }
    const workspace = options.getWorkspace();

    return chain([addDependency(workspace, project, dep, dev)]);
  };
}
Example #25
Source File: index.ts    From cli with Apache License 2.0 6 votes vote down vote up
export function setupDependencies(_options: CoveoSchema): Rule {
  return () =>
    chain([
      addToPackageJson('@angular/material', '~13.0.0'),
      addToPackageJson('@coveo/headless'),
      addToPackageJson('@coveo/search-token-server'),
      addToPackageJson('get-port', '^5.1.1'),
      addToPackageJson('dotenv', '^8.6.0'),
      addToPackageJson('concurrently'),
      runPackageInstallTask(),
      allowCommonJsDependencies(_options),
      configureStartCommand(_options),
    ]);
}
Example #26
Source File: index.ts    From elements with MIT License 5 votes vote down vote up
export function ngAdd(): Rule {
  return chain([
    addIcons(),
    // install freshly added dependencies
    installNodeDeps(),
  ]);
}
Example #27
Source File: schematic.ts    From nx-plugins with MIT License 5 votes vote down vote up
export default function (): Rule {
  return async (host: Tree, context: SchematicContext): Promise<Rule> => {
    const workspace = await getWorkspace(host);
    const applications = getApplications(workspace, host);
    const questions: any[] = [];

    if (applications.length === 0) {
      context.logger.log('info', 'no applications found');
      return chain([]);
    }

    context.logger.log(
      'info',
      `We found ${applications.length} supported applications.`
    );

    const choosenApplications = await prompt<{
      setupApplications: {
        projectName: string;
        applicationType: ApplicationType;
      }[];
    }>({
      ...QUESTIONS.setupApplications,
      choices: applications.map((app) => ({
        name: `${app.projectName} (${app.applicationType})`,
        value: app,
      })),
      result: function (result: string) {
        return Object.values(this.map(result));
      },
    } as any);

    if (choosenApplications.setupApplications.length === 0) {
      context.logger.log('info', 'No applications selected. Skipping setup');
      return chain([]);
    }

    const { provider } = await prompt<{ provider: PROVIDER }>([
      QUESTIONS.whichProvider,
    ]);

    switch (provider) {
      case PROVIDER.AWS:
        questions.push(QUESTIONS.awsProfile, QUESTIONS.awsRegion);
        break;

      case PROVIDER.AZURE:
        questions.push(QUESTIONS.azureLocation);
        break;

      case PROVIDER.GOOGLE_CLOUD_PLATFORM:
        questions.push(QUESTIONS.gcpProjectId);
        break;

      default:
        break;
    }

    const options = await prompt(questions);

    return chain(
      choosenApplications.setupApplications.map((application) => {
        return externalSchematic('@dev-thought/nx-deploy-it', 'init', {
          ...options,
          provider,
          project: application.projectName,
        });
      })
    );
  };
}
Example #28
Source File: index.ts    From angular-git-info with MIT License 5 votes vote down vote up
function addVersionGeneratorFile(): Rule {
    return (tree: Tree, context: SchematicContext) => {
        context.logger.debug('adding file to host dir');

        return chain([mergeWith(apply(url('./files'), [move('./')]))])(tree, context);
    };
}
Example #29
Source File: index.ts    From source-map-analyzer with MIT License 5 votes vote down vote up
export function ngAdd(options: NgAddOptions): Rule {
    return async (host: Tree) => {
        const workspace = await getWorkspace(host);

        // Get project name 
        if (!options.project) {
            if (workspace.extensions.defaultProject) {
                options.project = workspace.extensions.defaultProject as string;
            } else {
                throw new SchematicsException(
                    'No Angular project selected and no default project in the workspace'
                );
            }
        }

        // Validating project name
        const project = workspace.projects.get(options.project);
        if (!project) {
            throw new SchematicsException(`The specified Angular project is not defined in this workspace`);
        }

        // Checking if it is application
        if (project.extensions['projectType'] !== 'application') {
            throw new SchematicsException(`source-map-analyzer requires an Angular project type of "application" in angular.json`);
        }
        
        const outputPath: string | undefined = project.targets.get('build')?.options?.outputPath as string;

        if (!outputPath) {
            const message: string = `Cannot read the output path(architect.build.options.outputPath) of the Angular project "${options.project}" in angular.json`;
            throw new SchematicsException(message);
        }

        var targetDefinition: TargetDefinition = {
            builder: "@ngx-builders/analyze:analyze",
            options: {
                outputPath: outputPath
            }
        }

        project.targets.add({ name: 'analyze', ...targetDefinition });

        return chain([updateWorkspace(workspace)]);
    };
}