@angular-devkit/schematics#url TypeScript Examples

The following examples show how to use @angular-devkit/schematics#url. 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) => {
        const sourceTemplates = url('./files'); // 使用範本
        const sourceParametrizedTemplates = apply(sourceTemplates, [
            // renameTemplateFiles(), // 去掉后缀
            applyTemplates({
                ...strings,
                ..._options, // 使用者所輸入的參數
            })
        ]);
        return mergeWith(sourceParametrizedTemplates);
    };
}
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: 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 #4
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) => {
    const sourceTemplates = url('./files'); // 使用範本
    const sourceParametrizedTemplates = apply(sourceTemplates, [
      // renameTemplateFiles(), // 去掉后缀
      applyTemplates({
        ...strings,
        ..._options, // 使用者所輸入的參數
      })
    ]);
    return mergeWith(sourceParametrizedTemplates);
  };
}
Example #5
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) => {
    const sourceTemplates = url('./files'); // 使用範本
    const sourceParametrizedTemplates = apply(sourceTemplates, [
      // renameTemplateFiles(), // 去掉后缀
      applyTemplates({
        ...strings,
        ..._options, // 使用者所輸入的參數
      })
    ]);
    return mergeWith(sourceParametrizedTemplates);
  };
}
Example #6
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 #7
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 #8
Source File: index.ts    From ng-ant-admin with MIT License 6 votes vote down vote up
function oneLevelRule(_options: any): Rule {
    return (tree: Tree, _context: SchematicContext) => {
        const sourceTemplates = url('./files'); // 使用範本
        const sourceParametrizedTemplates = apply(sourceTemplates, [
            // renameTemplateFiles(), // 去掉后缀
            applyTemplates({
                ...strings,
                ..._options, // 使用者所輸入的參數
            })
        ]);
        return mergeWith(sourceParametrizedTemplates);
    };

}
Example #9
Source File: templates.ts    From cli with Apache License 2.0 6 votes vote down vote up
/**
 * Schematic rule that copies files into the Angular project.
 *
 * @export
 * @param {CoveoSchema} _options
 * @param {string} [workspaceRootPath='./']      The root path from which the applyTemplates function will start pasting files.
 *                                               The default value is "./" because the file structure is already defined within the ./files directories
 * @param {string} [templateFilePath='./files']  Path containing the files to copy into the Angular project
 * @returns {Rule}
 */
export function createFiles(
  _options: CoveoSchema,
  workspaceRootPath = './',
  templateFilePath = './files',
  customFilter = isNotNodeModuleFile
): Rule {
  return (tree: Tree, context: SchematicContext) => {
    const templateSource = apply(url(templateFilePath), [
      filter(customFilter),
      applyTemplates({
        ..._options,
      }),
      move(normalize(workspaceRootPath)),
      overwriteIfExists(tree),
    ]);

    const rule = mergeWith(templateSource);
    return rule(tree, context);
  };
}
Example #10
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 #11
Source File: index.ts    From garment with MIT License 5 votes vote down vote up
export default function(options: PackageSchematicOptions): Rule {
  return (_tree: Tree, context: SchematicContext) => {
    const { name } = options;

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

    const directory = 'plugins';

    const dashedName = strings.dasherize(name);
    const projectName = 'runner-' + dashedName;

    const packagePath = Path.join(directory, projectName);

    context.addTask(
      new NodePackageInstallTask({
        workingDirectory: packagePath,
        packageManager: 'yarn'
      })
    );

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

    return chain([
      mergeWith(source),
      addPackageJsonDependencies(
        `${packagePath}/package.json`,
        'core/runner/package.json',
        'utils/fixture-helper/package.json'
      ),
      addProjectToGarmentJson({
        garmentJsonPath: '/garment.json',
        name: projectName,
        path: packagePath,
        extendProjects: ['tspackage', 'copy-other-files']
      })
    ]);
  };
}
Example #12
Source File: index.ts    From form-schematic with MIT License 5 votes vote down vote up
// You don't have to export the function as default. You can also have more than one rule factory
// per file.
export function forms(_options: OptionsFormSchema): Rule {
	return (tree: Tree, _context: SchematicContext) => {
		// Log
		// context.logger.info('Info message');
		// context.logger.warn('Warn message');
		// context.logger.error('Error message');
		const workspaceConfig = tree.read('/angular.json');

		if (!workspaceConfig) {
			throw new NotValidAngularWorkspace();
		}

		const workspaceContent = workspaceConfig.toString();

		const workspace: workspace.WorkspaceSchema = JSON.parse(
			workspaceContent
		);

		if (!_options.project) {
			_options.project = workspace.defaultProject || '';
		}

		const projectName = _options.project;
		const project = workspace.projects[projectName];

		const jsonFormConfig = tree.read(`${_options.config}`);

		if (!jsonFormConfig) {
			throw new FormJsonNotFoundError();
		}

		const jsonFormContent = jsonFormConfig.toString();

		const formJsonObj = new FormJson(JSON.parse(jsonFormContent));

		const projectType =
			project.projectType === 'application'
				? ProjetTypeEnum.APP
				: ProjetTypeEnum.LIB;

		if (!_options.path) {
			_options.path = `${project.sourceRoot}/${projectType}`;
		}
		const parsedOptions = parseName(_options.path, _options.name);
		_options = { ..._options, ...parsedOptions };

		const templateSource = apply(url('./templates/forms'), [
			renameTemplateFiles(),
			template({
				...strings,
				..._options,
				formJsonObj
			}),
			move(normalize((_options.path + '/' + _options.name) as string))
		]);

		return chain([
			branchAndMerge(chain([mergeWith(templateSource)])),
			addTreeModulesToModule(_options),
			addDeclarationsToModule(_options)
		])(tree, _context);
	};
}
Example #13
Source File: index.ts    From open-source with MIT License 5 votes vote down vote up
export default function (options: ComponentOptions): Rule {
   return async (host: Tree) => {
     const workspace = await getWorkspace(host);
     const project = workspace.projects.get(options.project as string);

     if (options.path === undefined && project) {
       options.path = buildDefaultPath(project);
     }

     if (options.prefix === undefined && project) {
       options.prefix = project.prefix || '';
     }

     options.module = findModuleFromOptions(host, options);

     const parsedPath = parseName(options.path as string, options.name);
     options.name = parsedPath.name;
     options.path = parsedPath.path;
     options.selector =
       options.selector || buildSelector(options, (project && project.prefix) || '');

     validateName(options.name);
     validateHtmlSelector(options.selector);

     const templateSource = apply(url('./files'), [
       options.skipTests ? filter((path) => !path.endsWith('.spec.ts.template')) : noop(),
       applyTemplates({
         ...strings,
         'if-flat': (s: string) => (options.flat ? '' : s),
         ...options,
       }),
       !options.type
         ? forEach(((file) => {
             return file.path.includes('..')
               ? {
                   content: file.content,
                   path: file.path.replace('..', '.'),
                 }
               : file;
           }) as FileOperator)
         : noop(),
       move(parsedPath.path),
     ]);

     return chain([
       addDeclarationToNgModule(options),
       mergeWith(templateSource),
       options.lintFix ? applyLintFix(options.path) : noop(),
     ]);
   };
 }
Example #14
Source File: index.ts    From open-source with MIT License 5 votes vote down vote up
export default function (options: ModuleOptions): Rule {
  return async (host: Tree) => {
    const workspace = await getWorkspace(host);
    const project = workspace.projects.get(options.project as string);

    if (options.path === undefined) {
      options.path = await createDefaultPath(host, options.project as string);
    }

    if (options.module) {
      options.module = findModuleFromOptions(host, options);
    }

    if (options.prefix === undefined) {
      options.prefix = project?.prefix || '';
    }

    const parsedPath = parseName(options.path, options.name);
    options.name = parsedPath.name;
    options.path = parsedPath.path;

    const templateSource = apply(url('./files'), [
      applyTemplates({
        ...strings,
        'if-flat': (s: string) => (options.flat ? '' : s),
        ...options,
      }),
      move(parsedPath.path),
    ]);
    const moduleDasherized = strings.dasherize(options.name);
    const controlDasherized = strings.dasherize(options.controlName);
    const controlPath = `${options.path}/${
      !options.flat ? `${moduleDasherized}/` : ''
    }${options.controlPath}${options.flat ? `/${controlDasherized}` : ''}`;

    const controlOptions: ControlOptions = {
      project: options.project,
      path: controlPath,
      name: controlDasherized,
      type: options.type,
      id: options.id || 'CONTROL',
      instance: options.instance || 'Control',
      flat: options.flat,
      prefix: options.prefix,
      prefixInterface: options.prefixInterface,
      prefixClass: options.prefixClass,
    };

    return chain([
      mergeWith(templateSource),
      schematic('control', controlOptions),
      options.lintFix ? applyLintFix(options.path) : noop(),
    ]);
  };
}
Example #15
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 #16
Source File: index.ts    From garment with MIT License 5 votes vote down vote up
export default function(options: Options): Rule {
  return (_tree: Tree, context: SchematicContext) => {
    const { name } = options;
    if (!options.name) {
      throw new SchematicsException('name option is required.');
    }

    const directory = 'plugins';

    const dashedName = strings.dasherize(name);
    const projectName = dashedName;

    context.logger.info(`Creating project called "${projectName}"...`);

    const packagePath = Path.join(directory, projectName);

    context.addTask(
      new NodePackageInstallTask({
        workingDirectory: packagePath,
        packageManager: 'yarn'
      })
    );

    let source = apply(url('../../templates/plugin'), [
      applyTemplates({
        name,
        ...strings
      }),
      move(packagePath)
    ]);

    return chain([
      mergeWith(source),
      addPackageJsonDependencies(
        `${packagePath}/package.json`,
        'core/workspace/package.json'
      ),
      addProjectToGarmentJson({
        garmentJsonPath: '/garment.json',
        name: projectName,
        path: packagePath,
        extendProjects: ['tspackage']
      })
    ]);
  };
}
Example #17
Source File: index.ts    From garment with MIT License 5 votes vote down vote up
export default function(options: PackageSchematicOptions): Rule {
  return (tree: Tree, context: SchematicContext) => {
    const { name, directory } = options;
    if (!options.name) {
      throw new SchematicsException('name option is required.');
    }
    if (!tree.getDir('.').subdirs.includes(directory as any)) {
      throw new SchematicsException(`Directory "${directory}" doesn't exist`);
    }

    const dashedName = strings.dasherize(name);
    const packagePath = Path.join(directory, dashedName);

    context.addTask(
      new NodePackageInstallTask({
        workingDirectory: packagePath,
        packageManager: 'yarn'
      })
    );

    let source = apply(url('../../templates/package'), [
      applyTemplates({
        packageName: dashedName,
        dot: '.',
        camelize: strings.camelize,
        dasherize: strings.dasherize
      }),
      move(packagePath)
    ]);

    return chain([
      mergeWith(source),
      addProjectToGarmentJson({
        garmentJsonPath: '/garment.json',
        name: dashedName,
        path: packagePath,
        extendProjects: ['tspackage']
      })
    ]);
  };
}