export function addResetCss(host: Tree): boolean {
    const config = getWorkspace(host);
    const project = config.projects[config.defaultProject] as WorkspaceProject<ProjectType.Application>;
    let addPackage;

    const styleExts = ['scss', 'sass', 'css', 'less', 'styl'];
    const styleExt = styleExts.find(ext => host.exists(path.posix.join(project.sourceRoot, `styles.${ext}`)));
    if (!styleExt) {
        return false;
    }
    const stylesFile = path.posix.join(project.sourceRoot, `styles.${styleExt}`);

    switch (styleExt) {
    case 'sass':
    case 'scss':
        let content = host.read(stylesFile).toString();
        if (content.indexOf(`~minireset.css/minireset`) === -1) {
            content = scssImport + content;
            host.overwrite(stylesFile, content);
            addPackage = resetPackage;
        }
        break;
    case 'css':
    case 'less':
    case 'styl':
        if (!project.architect ||
            !project.architect.build ||
            project.projectType !== ProjectType.Application) {
            return false;
        }
        if (project.architect.build.options.styles) {
            project.architect.build.options.styles =
                [cssImport, ...project.architect.build.options.styles];
        } else {
            project.architect.build.options.styles = [cssImport];
        }
        host.overwrite(getWorkspacePath(host), JSON.stringify(config, null, 2));
        addPackage = resetPackage;
        break;
    default:
        break;
    }

    if (addPackage) {
        const targetFile = 'package.json';
        if (host.exists(targetFile)) {
            const pkgJson = JSON.parse(host.read(targetFile).toString());
            pkgJson.dependencies = Object.assign({}, addPackage, pkgJson.dependencies);
            host.overwrite(targetFile, JSON.stringify(pkgJson, null, 2) + '\n');
            return true;
        }
    }
    return false;
}
Example #2
0
  return (tree: Tree, context: SchematicContext) => {
    const pkgPath = '/package.json';
    const buffer = tree.read(pkgPath);
    if (buffer == null) {
      throw new SchematicsException('Could not read package.json');
    }
    const content = buffer.toString();
    const pkg = JSON.parse(content);

    if (pkg === null || typeof pkg !== 'object' || Array.isArray(pkg)) {
      throw new SchematicsException('Error reading package.json');
    }

    const dependencyCategories = ['dependencies', 'devDependencies'];

    dependencyCategories.forEach(category => {
      const packageName = `@ngrx/${name}`;

      if (pkg[category] && pkg[category][packageName]) {
        const firstChar = pkg[category][packageName][0];
        const suffix = match(firstChar, '^') || match(firstChar, '~');

        // TODO: remove beta
        pkg[category][packageName] = `${suffix}6.0.0`;
      }
    });

    tree.overwrite(pkgPath, JSON.stringify(pkg, null, 2));
    context.addTask(new NodePackageInstallTask());

    return tree;
  };
Example #3
0
    return new Observable<Tree>(obs => {
      const input = new Readable({
        encoding: 'utf8',
        read(): void {
          this.push(buffer);
          this.push(null);
        },
      });

      const chunks: Array<Buffer> = [];
      const output = new Writable({
        write(chunk: string | Buffer, encoding: string, callback: Function): void {
          chunks.push(typeof chunk === 'string' ? Buffer.from(chunk, encoding) : chunk);
          callback();
        },
        final(callback: (error?: Error) => void): void {
          const full = Buffer.concat(chunks);
          host.overwrite(path, full.toString());
          callback();
          obs.next(host);
          obs.complete();
        },
      });

      input.pipe(rewriter).pipe(output);
    });
Example #4
0
  return (host: Tree) => {
    host.overwrite('src/app/app.component.html', `<a href="https://github.com/NG-ZORRO/ng-zorro-antd" target="_blank" style="display: flex;align-items: center;justify-content: center;height: 100%;width: 100%;">
  <img height="400" src="https://img.alicdn.com/tfs/TB1MGSRv21TBuNjy0FjXXajyXXa-89-131.svg">
</a>
`);
    return host;
  };
Example #5
0
  return (host: Tree, context: SchematicContext) => {
    const workspace = getWorkspace(host);
    const project = workspace.projects[options.project as string];
    let path: string;
    if (project && project.architect && project.architect.build &&
        project.architect.build.options.index) {
      path = project.architect.build.options.index;
    } else {
      throw new SchematicsException('Could not find index file for the project');
    }
    const buffer = host.read(path);
    if (buffer === null) {
      throw new SchematicsException(`Could not read index file: ${path}`);
    }
    const content = buffer.toString();
    const lines = content.split('\n');
    let closingHeadTagLineIndex = -1;
    let closingHeadTagLine = '';
    let closingBodyTagLineIndex = -1;
    let closingBodyTagLine = '';
    lines.forEach((line: string, index: number) => {
      if (/<\/head>/.test(line) && closingHeadTagLineIndex === -1) {
        closingHeadTagLine = line;
        closingHeadTagLineIndex = index;
      }

      if (/<\/body>/.test(line) && closingBodyTagLineIndex === -1) {
        closingBodyTagLine = line;
        closingBodyTagLineIndex = index;
      }
    });

    const headTagIndent = getIndent(closingHeadTagLine) + '  ';
    const itemsToAddToHead = [
      '<link rel="manifest" href="manifest.json">',
      '<meta name="theme-color" content="#1976d2">',
    ];

    const textToInsertIntoHead = itemsToAddToHead
      .map(text => headTagIndent + text)
      .join('\n');

    const bodyTagIndent = getIndent(closingBodyTagLine) + '  ';
    const itemsToAddToBody
      = '<noscript>Please enable JavaScript to continue using this application.</noscript>';

    const textToInsertIntoBody = bodyTagIndent + itemsToAddToBody;

    const updatedIndex = [
      ...lines.slice(0, closingHeadTagLineIndex),
      textToInsertIntoHead,
      ...lines.slice(closingHeadTagLineIndex, closingBodyTagLineIndex),
      textToInsertIntoBody,
      ...lines.slice(closingBodyTagLineIndex),
    ].join('\n');

    host.overwrite(path, updatedIndex);

    return host;
  };
Example #6
0
    (tree: Tree) => {
      const packageJsonContent = tree.read('/package.json');
      if (!packageJsonContent) {
        throw new SchematicsException('Could not find package.json.');
      }
      const packageJson = parseJson(packageJsonContent.toString(), JsonParseMode.Strict);
      if (packageJson === null || typeof packageJson !== 'object' || Array.isArray(packageJson)) {
        throw new SchematicsException('Could not parse package.json.');
      }

      for (const field of kPackageJsonDependencyFields) {
        const deps = packageJson[field];
        if (!deps || typeof deps !== 'object' || Array.isArray(deps)) {
          continue;
        }

        for (const depName of Object.keys(deps)) {
          if (allVersions[depName]) {
            deps[depName] = allVersions[depName];
          }
        }
      }

      tree.overwrite('/package.json', JSON.stringify(packageJson, null, 2) + '\n');

      return tree;
    },
Example #7
0
  return (host: Tree) => {
    const workspace = getWorkspace(host);
    if (!workspace.projects[options.clientProject]) {
      throw new SchematicsException(`Client app ${options.clientProject} not found.`);
    }

    const clientProject = workspace.projects[options.clientProject];
    const projectTargets = getProjectTargets(clientProject);

    const builderOptions: JsonObject = {
      outputPath: `dist/${options.clientProject}-server`,
      main: `${clientProject.root}src/main.server.ts`,
      tsConfig: join(tsConfigDirectory, `${options.tsconfigFileName}.json`),
    };
    const serverTarget: JsonObject = {
      builder: '@angular-devkit/build-angular:server',
      options: builderOptions,
    };
    projectTargets.server = serverTarget;

    const workspacePath = getWorkspacePath(host);

    host.overwrite(workspacePath, JSON.stringify(workspace, null, 2));

    return host;
  };
Example #8
0
  return (host: Tree, context: SchematicContext) => {

    if (host.exists('package.json')) {
      const jsonStr = host.read('package.json') !.toString('utf-8');
      const json = JSON.parse(jsonStr);

      // If there are no dependencies, create an entry for dependencies.
      const type = 'dependencies';
      if (!json[type]) {
        json[type] = {};
      }

      // If not already present, add the dependency.
      const pkg = 'document-register-element';
      const version = '^1.7.2';
      if (!json[type][pkg]) {
        json[type][pkg] = version;
      }

      // Write the JSON back to package.json
      host.overwrite('package.json', JSON.stringify(json, null, 2));
      context.logger.log('info', 'Added `document-register-element` as a dependency.');

      // Install the dependency
      context.addTask(new NodePackageInstallTask());
    }

    return host;
  };
Example #9
0
File: index.ts Project: iwe7/devkit
  return (host: Tree) => {
    const workspace = getWorkspace(host);
    if (!workspace.projects[options.clientProject]) {
      throw new SchematicsException(`Client app ${options.clientProject} not found.`);
    }

    const clientProject = workspace.projects[options.clientProject];
    if (!clientProject.architect) {
      throw new Error('Client project architect not found.');
    }

    const builderOptions: JsonObject = {
      outputPath: `dist/${options.clientProject}-server`,
      main: `${clientProject.root}src/main.server.ts`,
      tsConfig: `${clientProject.root}src/tsconfig.server.json`,
    };
    const serverTarget: JsonObject = {
      builder: '@angular-devkit/build-angular:server',
      options: builderOptions,
    };
    clientProject.architect.server = serverTarget;

    const workspacePath = getWorkspacePath(host);

    host.overwrite(workspacePath, JSON.stringify(workspace, null, 2));

    return host;
  };
Example #10
0
  return (host: Tree, context: SchematicContext) => {
    const polyfillName = 'custom-elements';
    const polyfillPath = 'node_modules/@webcomponents/custom-elements/src/native-shim.js';

    try {
      const angularJsonFile = host.read('angular.json');

      if (angularJsonFile) {
        const angularJsonFileObject = JSON.parse(angularJsonFile.toString('utf-8'));
        const project = options.project ? options.project : Object.keys(angularJsonFileObject['projects'])[0];
        const projectObject = angularJsonFileObject.projects[project];
        const targets = projectObject.targets ? projectObject.targets : projectObject.architect;
        const scripts = targets.build.options.scripts;

        scripts.push({
          input: polyfillPath
        });
        host.overwrite('angular.json', JSON.stringify(angularJsonFileObject, null, 2));
      }
    } catch (e) {
      context.logger.log('error', `🚫 Failed to add the polyfill "${polyfillName}" to scripts`);
    }

    context.logger.log('info', `✅️ Added "${polyfillName}" polyfill to scripts`);

    return host;
  };
Example #11
0
  return (host: Tree, context: SchematicContext) => {
    context.logger.info(`Updating karma configuration`);
    try {
      const karmaPath = config && config.test && config.test.karma && config.test.karma.config
        ? config.test.karma.config
        : defaults.karma;
      const buffer = host.read(karmaPath);
      if (buffer !== null) {
        let content = buffer.toString();
        // Replace the 1.0 files and preprocessor entries, with and without comma at the end.
        // If these remain, they will cause the `ng test` to fail.
        content = content.replace(`{ pattern: './src/test.ts', watched: false },`, '');
        content = content.replace(`{ pattern: './src/test.ts', watched: false }`, '');
        content = content.replace(`'./src/test.ts': ['@angular/cli'],`, '');
        content = content.replace(`'./src/test.ts': ['@angular/cli']`, '');
        content = content.replace(/angularCli[^}]*},?/, '');
        // Replace 1.x plugin names.
        content = content.replace(/@angular\/cli/g, '@angular-devkit/build-angular');
        // Replace code coverage output path.
        content = content.replace('reports',
          `dir: require('path').join(__dirname, 'coverage'), reports`);
        host.overwrite(karmaPath, content);
      }
    } catch { }

    return host;
  };
Example #12
0
File: index.ts Project: iwe7/devkit
  return (host: Tree, context: SchematicContext) => {

    const workspacePath = getWorkspacePath(host);
    const workspace = getWorkspace(host);
    const project = workspace.projects[options.project as string];

    if (!project) {
      throw new Error(`Project is not defined in this workspace.`);
    }

    const assetEntry = join(normalize(project.root), 'src', 'manifest.json');

    if (!project.architect) {
      throw new Error(`Architect is not defined for this project.`);
    }

    const architect = project.architect;

    ['build', 'test'].forEach((target) => {

      const applyTo = architect[target].options;

      if (!applyTo.assets) {
        applyTo.assets = [assetEntry];
      } else {
        applyTo.assets.push(assetEntry);
      }

    });

    host.overwrite(workspacePath, JSON.stringify(workspace, null, 2));

    return host;
  };
Example #13
0
File: index.ts Project: iwe7/devkit
  return (host: Tree) => {
    const packageJsonPath = 'package.json';

    if (!host.exists('package.json')) { return host; }

    const source = host.read('package.json');
    if (!source) { return host; }

    const sourceText = source.toString('utf-8');
    const json = JSON.parse(sourceText);

    if (!json['devDependencies']) {
      json['devDependencies'] = {};
    }

    json.devDependencies = {
      '@angular/compiler-cli': latestVersions.Angular,
      '@angular-devkit/build-angular': latestVersions.DevkitBuildAngular,
      'typescript': latestVersions.TypeScript,
      // De-structure last keeps existing user dependencies.
      ...json.devDependencies,
    };

    host.overwrite(packageJsonPath, JSON.stringify(json, null, 2));

    return host;
  };
function updateFile(remoteFiles: Tree, { path, file }: { path: string, file: FileEntry }) {
    if (!file) {
        console.log(`missing: ${path}`)
    }

    remoteFiles.overwrite(path, file.content);
}
Example #15
0
  return (host: Tree, context: SchematicContext) => {
    context.logger.debug('updating config file.');
    const workspacePath = getWorkspacePath(host);

    const workspace = getWorkspace(host);

    const project = workspace.projects[options.project as string];

    if (!project) {
      throw new Error(`Project is not defined in this workspace.`);
    }

    if (!project.architect) {
      throw new Error(`Architect is not defined for this project.`);
    }

    if (!project.architect[options.target]) {
      throw new Error(`Target is not defined for this project.`);
    }

    let applyTo = project.architect[options.target].options;

    if (options.configuration &&
        project.architect[options.target].configurations &&
        project.architect[options.target].configurations[options.configuration]) {
      applyTo = project.architect[options.target].configurations[options.configuration];
    }

    applyTo.serviceWorker = true;

    host.overwrite(workspacePath, JSON.stringify(workspace, null, 2));

    return host;
  };
  return (tree: Tree, _context: SchematicContext) => {

    const localFiles = url("./files")(_context) as Tree;
    const updateFiles = getUpdateFiles(localFiles);
    const createFiles = getCreateFiles(localFiles);

    if (updateFiles.length > 0) {
        updateFiles.forEach(f => updateFile(tree, f));
    }

    if (createFiles.length > 0) {
        createFiles.forEach(f => createFile(tree, f));
    }

    const config = tree.read(".angular-cli.json");
    if (config) {
        const asJson = JSON.parse(config.toString());
        asJson.apps[0].assets.push("config.json");
        tree.overwrite(".angular-cli.json", JSON.stringify(asJson, null, 2));
    }

    // angular 6
    const configA6 = tree.read("angular.json");
    if (configA6) {
        const asJson = JSON.parse(configA6.toString());

        Object.entries(asJson.projects).forEach(([,value] : any) => {
            const options = value.architect &&
                value.architect.build &&
                value.architect.build.options;

            const assets = options && options.assets;
            if (assets) {
                assets.push("src/config.json");
            }
            const styles = options && options.styles;
            if (styles) {
                styles.push("src/theme.css");
            }
        });

        tree.overwrite("angular.json", JSON.stringify(asJson, null, 2));
    }

    return tree;
  };
Example #17
0
 /** Overwrites a target builder for the workspace in the given tree */
 function overwriteTargetBuilder(tree: Tree, targetName: string, newBuilder: string) {
   const workspace = getWorkspace(tree);
   const project = getProjectFromWorkspace(workspace);
   const targetConfig = project.architect && project.architect[targetName] ||
                        project.targets && project.targets[targetName];
   targetConfig['builder'] = newBuilder;
   tree.overwrite('/angular.json', JSON.stringify(workspace, null, 2));
 }
Example #18
0
 dir.visit((path, entry) => {
     if (path.endsWith('.' + ext)) {
         let content = entry.content.toString();
         if (content.indexOf(themeImport) !== -1) {
             content = content.replace(themeImport, newThemeImport);
             host.overwrite(path, content);
         }
     }
 });
Example #19
0
function enableWebAnimationsAndGridSupport(tree: Tree, targetFile: string, polyfillsData: any): void {
  // Target the web-animations-js commented import statement and uncomment it.
  const webAnimationsLine = '// import \'web-animations-js\';';
  polyfillsData = polyfillsData.replace(webAnimationsLine,
    webAnimationsLine.substring(3, webAnimationsLine.length));

  polyfillsData = addIgxGridSupportForIe(polyfillsData);
  tree.overwrite(targetFile, polyfillsData);
}
Example #20
0
  return (host: Tree, context: SchematicContext) => {
    // TODO: use JsonAST
    // const workspacePath = '/angular.json';
    // const workspaceBuffer = host.read(workspacePath);
    // if (workspaceBuffer === null) {
    //   throw new SchematicsException(`Configuration file (${workspacePath}) not found.`);
    // }
    // const workspaceJson = parseJson(workspaceBuffer.toString());
    // if (workspaceJson.value === null) {
    //   throw new SchematicsException(`Unable to parse configuration file (${workspacePath}).`);
    // }
    let projectRoot = options.projectRoot !== undefined
      ? options.projectRoot
      : `${workspace.newProjectRoot}/${options.name}`;
    if (projectRoot !== '' && !projectRoot.endsWith('/')) {
      projectRoot += '/';
    }
    // tslint:disable-next-line:no-any
    const project: any = {
      root: projectRoot,
      projectType: 'application',
      targets: {
        e2e: {
          builder: '@angular-devkit/build-angular:protractor',
          options: {
            protractorConfig: `${projectRoot}protractor.conf.js`,
            devServerTarget: `${options.relatedAppName}:serve`,
          },
          configurations: {
            production: {
              devServerTarget: `${options.relatedAppName}:serve:production`,
            },
          },
        },
        lint: {
          builder: '@angular-devkit/build-angular:tslint',
          options: {
            tsConfig: `${projectRoot}tsconfig.e2e.json`,
            exclude: [
              '**/node_modules/**',
            ],
          },
        },
      },
    };
    // tslint:disable-next-line:no-any
    // const projects: JsonObject = (<any> workspaceAst.value).projects || {};
    // tslint:disable-next-line:no-any
    // if (!(<any> workspaceAst.value).projects) {
    //   // tslint:disable-next-line:no-any
    //   (<any> workspaceAst.value).projects = projects;
    // }

    // TODO: throw if the project already exist.
    workspace.projects[options.name] = project;
    host.overwrite(getWorkspacePath(host), JSON.stringify(workspace, null, 2));
  };
Example #21
0
function updateJsonFile<T>(host: Tree, path: string, callback: UpdateJsonFn<T>): Tree {
  const source = host.read(path);
  if (source) {
    const sourceText = source.toString('utf-8');
    const json = parseJson(sourceText);
    callback(json as {} as T);
    host.overwrite(path, JSON.stringify(json, null, 2));
  }

  return host;
}
Example #22
0
    /** Writes a specific style file to the workspace in the given tree */
    function writeStyleFileToWorkspace(tree: Tree, stylePath: string) {
      const workspace = getWorkspace(tree);
      const project = getProjectFromWorkspace(workspace);
      const buildOptions = getProjectTargetOptions(project, 'build');

      if (!buildOptions.styles) {
        buildOptions.styles = [stylePath];
      } else {
        buildOptions.styles.push(stylePath);
      }

      tree.overwrite('/angular.json', JSON.stringify(workspace, null, 2));
    }
Example #23
0
  return (host: Tree, context: SchematicContext) => {
    const tsConfigPath = '/tsconfig.json';
    const buffer = host.read(tsConfigPath);
    if (!buffer) {
      return;
    }

    const tsCfgAst = parseJsonAst(buffer.toString(), JsonParseMode.Loose);
    if (tsCfgAst.kind !== 'object') {
      throw new SchematicsException('Invalid root tsconfig. Was expecting an object');
    }

    const compilerOptionsAstNode = findPropertyInAstObject(tsCfgAst, 'compilerOptions');
    if (!compilerOptionsAstNode || compilerOptionsAstNode.kind != 'object') {
      throw new SchematicsException(
        'Invalid root tsconfig "compilerOptions" property; expected an object.',
      );
    }

    if (
      findPropertyInAstObject(compilerOptionsAstNode, 'baseUrl') &&
      findPropertyInAstObject(compilerOptionsAstNode, 'module')
    ) {
      return host;
    }

    const compilerOptions = compilerOptionsAstNode.value;
    const { baseUrl = './', module = 'es2015'} = compilerOptions;

    const validBaseUrl = ['./', '', '.'];
    if (!validBaseUrl.includes(baseUrl as string)) {
      const formattedBaseUrl = validBaseUrl.map(x => `'${x}'`).join(', ');
      context.logger.warn(tags.oneLine
        `Root tsconfig option 'baseUrl' is not one of: ${formattedBaseUrl}.
        This might cause unexpected behaviour when generating libraries.`,
      );
    }

    if (module !== 'es2015') {
      context.logger.warn(
        `Root tsconfig option 'module' is not 'es2015'. This might cause unexpected behaviour.`,
      );
    }

    compilerOptions.module = module;
    compilerOptions.baseUrl = baseUrl;

    host.overwrite(tsConfigPath, JSON.stringify(tsCfgAst.value, null, 2));

    return host;
  };
Example #24
0
  return (host: Tree) => {
    const tsLintPath = '/tslint.json';
    if (!host.exists(tsLintPath)) {
      return;
    }

    const rootTslintConfig = readTsLintConfig(parentHost, tsLintPath);
    const appTslintConfig = readTsLintConfig(host, tsLintPath);

    const recorder = host.beginUpdate(tsLintPath);
    rootTslintConfig.properties.forEach(prop => {
      if (findPropertyInAstObject(appTslintConfig, prop.key.value)) {
        // property already exists. Skip!
        return;
      }

      insertPropertyInAstObjectInOrder(
        recorder,
        appTslintConfig,
        prop.key.value,
        prop.value.value,
        2,
      );
    });

    const rootRules = findPropertyInAstObject(rootTslintConfig, 'rules');
    const appRules = findPropertyInAstObject(appTslintConfig, 'rules');

    if (!appRules || appRules.kind !== 'object' || !rootRules || rootRules.kind !== 'object') {
      // rules are not valid. Skip!
      return;
    }

    rootRules.properties.forEach(prop => {
      insertPropertyInAstObjectInOrder(
        recorder,
        appRules,
        prop.key.value,
        prop.value.value,
        4,
      );
    });

    host.commitUpdate(recorder);

    // this shouldn't be needed but at the moment without this formatting is not correct.
    const content = readTsLintConfig(host, tsLintPath);
    host.overwrite(tsLintPath, JSON.stringify(content.value, undefined, 2));
  };
Example #25
0
  return (host: Tree) => {
    const workspace = getWorkspace(host);
    const project = getProjectFromWorkspace(workspace, options.project);
    const appHTMLFile = `${project.sourceRoot}/app/app.component.html`;
    const buffer = host.read(appHTMLFile);

    if (!buffer) {
      console.log();
      console.error(chalk.red(`Could not find the project ${chalk.blue(appHTMLFile)} file inside of the ` +
        `workspace config`));
      return;
    }
    host.overwrite(appHTMLFile, bootstrapHTML);
    return host;
  };
Example #26
0
File: index.ts Project: iwe7/devkit
  return (host: Tree) => {
    const pkgPath = '/package.json';
    const buffer = host.read(pkgPath);
    if (buffer === null) {
      throw new SchematicsException('Could not find package.json');
    }

    const pkg = JSON.parse(buffer.toString());

    const ngCoreVersion = pkg.dependencies['@angular/core'];
    pkg.dependencies['@angular/platform-server'] = ngCoreVersion;

    host.overwrite(pkgPath, JSON.stringify(pkg, null, 2));

    return host;
  };
Example #27
0
  return (host: Tree, context: SchematicContext) => {

    if (workspace.projects[name]) {
      throw new Error(`Project '${name}' already exists in workspace.`);
    }

    // Add project to workspace.
    workspace.projects[name] = project;

    if (!workspace.defaultProject && Object.keys(workspace.projects).length === 1) {
      // Make the new project the default one.
      workspace.defaultProject = name;
    }

    host.overwrite(getWorkspacePath(host), JSON.stringify(workspace, null, 2));
  };
Example #28
0
export function addPackageToPackageJson(host: Tree, type: string, pkg: string, version: string) {
  if (host.exists('package.json')) {
    const sourceText = host.read('package.json')!.toString('utf-8');
    const json = JSON.parse(sourceText);
    if (!json[type]) {
      json[type] = {};
    }

    if (!json[type][pkg]) {
      json[type][pkg] = version;
    }

    host.overwrite('package.json', JSON.stringify(json, null, 2));
  }

  return host;
}
Example #29
0
File: index.ts Project: iwe7/devkit
  return (host: Tree, context: SchematicContext) => {
    const packageName = '@angular/service-worker';
    context.logger.debug(`adding dependency (${packageName})`);
    const buffer = host.read(packageJsonPath);
    if (buffer === null) {
      throw new SchematicsException('Could not find package.json');
    }

    const packageObject = JSON.parse(buffer.toString());

    const ngCoreVersion = packageObject.dependencies['@angular/core'];
    packageObject.dependencies[packageName] = ngCoreVersion;

    host.overwrite(packageJsonPath, JSON.stringify(packageObject, null, 2));

    return host;
  };
Example #30
0
    return (host: Tree, context: SchematicContext) => {
        context.logger.info(`Applying migration for Ignite UI for Angular to version ${version}`);

        const update = new UpdateChanges(__dirname, host, context);
        // update.applyChanges();

        // rename submodule imports
        for (const entryPath of update.tsFiles) {
            let content = host.read(entryPath).toString();
            if (content.indexOf('igniteui-angular/') !== -1) {
                const pos = getImportModulePositions(content, 'igniteui-angular/');
                for (let i = pos.length; i--;) {
                    content = content.slice(0, pos[i].start) + 'igniteui-angular' + content.slice(pos[i].end);
                }
                host.overwrite(entryPath, content);
            }
        }
    };