使用 Angular Schematics 复制文件夹及其内容

问题描述

我的库中有一个 fonts 文件夹,我想将其复制到 Angular 应用程序(更具体地说是 src/asset 文件夹),并在安装过程中或安装后使用 Angular Schematics。在 package.json 中运行简单的 cp 脚本不是一种选择。到目前为止,这是我的工厂:

export function addFonts(_options: any): Rule {
  return (tree: Tree,_context: SchematicContext) => {
    const workspaceConfigBuffer = tree.read('angular.json');
    if (!workspaceConfigBuffer) {
      throw new SchematicsException('Not an Angular CLI workspace');
    }
    const workspace = JSON.parse(workspaceConfigBuffer.toString());
    const projectName = workspace.defaultProject;
    const project = workspace.projects[projectName];
    const defaultProjectPath = `${project.sourceRoot}/${
      project.projectType === 'application' ? 'app' : 'lib'
    }`;
    const rawFontDir = tree.getDir(`${defaultProjectPath}/assets`);
    const results: string[] = [];
    tree.getDir('node_modules/@myNgLib/font-styles/fonts').visit(filePath => {
      results.push(filePath);
    });
    results.map(result => {
      const copyFonts = apply(url(`${result}`),[move(`${rawFontDir}`)]);
      console.log(rawFontDir);
      return mergeWith(copyFonts);
    });
    return tree;
  };
}

看来我没有更改树中的任何内容,因为当我运行它时,我收到消息 nothing to be done。有人可以帮忙吗?

解决方法

也许有人会有其他解决方案,但这是我的:

function addFonts(): Rule {
  return (tree: Tree,_context: SchematicContext) => {
    const workspaceConfigBuffer = tree.read('angular.json');
    if (!workspaceConfigBuffer) {
      throw new SchematicsException('Not an Angular CLI workspace');
    }
    const workspace = JSON.parse(workspaceConfigBuffer.toString());
    const projectName = workspace.defaultProject;
    const project = workspace.projects[projectName];
    const rawFontCopiesDir = tree.getDir(`${project.sourceRoot}/assets/fonts`);
    const nodeModulePath = 'node_modules/@myNgLib/font-styles/fonts';
    const files: string[] = [];
    tree.getDir(nodeModulePath).visit(filePath => {
      const file = filePath.split('/').slice(-1).toString();
      files.push(file);
    });
    const fs = require('fs');
    const parsedDir = JSON.parse(JSON.stringify(rawFontCopiesDir));
    const rootDir = parsedDir._tree._backend._root;
    fs.mkdir(`${rootDir}${rawFontCopiesDir.path}`,(err: any) => {
      if (err) {
        throw err;
      }
    });
    files.forEach(fileName => {
      fs.copyFile(
        `${rootDir}/${nodeModulePath}/${fileName}`,`${rootDir}${rawFontCopiesDir.path}/${fileName}`,(err: any) => {
          if (err) {
            throw err;
          }
        }
      );
    });
  };
}

基本使用 Node.js 方法结合 Schematics 进行文件/目录操作。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...