首页 > 解决方案 > 使用 Angular Schematics 复制文件夹及其内容

问题描述

我的库中有一个字体文件夹,我想src/asset在安装过程中或安装后使用 Angular Schematics 将其复制到 Angular 应用程序(更具体的文件夹)。在 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。任何人都可以帮忙吗?

标签: angularangular-schematics

解决方案


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

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 进行文件/目录操作。


推荐阅读