Copying folder and its contents with Angular Schematics

797 views Asked by At

I have a fonts folder in my library that I would like to copy over to Angular app (src/asset folder to be more specific), with Angular Schematics during or post install process. Running a simple cp script in package.json is not an option. Here is my factory so far:

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;
  };
}

It appears I'm not changing anything in the tree, since, when I run it I get the message Nothing to be done. Can anyone help?

1

There are 1 answers

0
Damiao On

Maybe someone will have other solution, but here is mine:

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;
          }
        }
      );
    });
  };
}

Basically used Node.js methods for file/directory manipulation in combination with Schematics.