angulartypescriptangular-schematics

How to access Angular project folder from a custom Angular schematic?


I am developing a custom Angular Schematic. This schematic has to access a folder inside the Angular project that will make use of the schematic. (The folder contains config files needed to generate my .ts files). The schematic will prompt the user for the path (stored in configFilesPath)

So far, I can only access this folder this way:

export const readConfigFilefromPath = (configFilesPath: string): string | undefined => {

  // ...

  const path = __dirname + "\\..\\..\\..\\..\\..\\src\\app\\" + configFilesPath;

  // ...
}

Is there a better way to access the path from the schematic?


Solution

  • It is interesting that you are trying to read external config files in your schematic, typically people try to pass all of the configuration in via the options.

    That being said, here's one way to do it - read in angular.json in your schematic and pull out the sourceRoot attribute for the project you care about:

    import { SchematicsException, Tree } from '@angular-devkit/schematics';
    import { experimental } from '@angular-devkit/core';
    
    function getSourceRoot(sProjectName: string, cTree: Tree) {
    
        const sWorkspaceConfig = cTree.read('/angular.json');
    
        if (!sWorkspaceConfig) {
            throw new SchematicsException('Could not find Angular workspace configuration');
        }
    
        const cWorkspace: experimental.workspace.WorkspaceSchema = JSON.parse(sWorkspaceConfig.toString());
    
        return cWorkspace.projects[sProjectName].sourceRoot;
    
    }
    

    Once you have the source root, you can append your relative path to the config file. If you want to avoid this sort of thing, the only thing I can think of is to create a schematic per config file and then hardcode the config into the schematic (perhaps not ideal for your situation).