How to use @angular-devkit/core - 10 common examples

To help you get started, we’ve selected a few @angular-devkit/core examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github johandb / svg-drawing-tool / node_modules / @angular / cli / lib / init.js View on Github external
const exitHandler = (options) => {
        if (options.cleanup) {
            const cpuProfile = profiler.stopProfiling();
            fs.writeFileSync(path.resolve(process.cwd(), process.env.NG_CLI_PROFILING || '') + '.cpuprofile', JSON.stringify(cpuProfile));
        }
        if (options.exit) {
            process.exit();
        }
    };
    process.on('exit', () => exitHandler({ cleanup: true }));
    process.on('SIGINT', () => exitHandler({ exit: true }));
    process.on('uncaughtException', () => exitHandler({ exit: true }));
}
let cli;
try {
    const projectLocalCli = node_1.resolve('@angular/cli', {
        checkGlobal: false,
        basedir: process.cwd(),
        preserveSymlinks: true,
    });
    // This was run from a global, check local version.
    const globalVersion = new semver_1.SemVer(packageJson['version']);
    let localVersion;
    let shouldWarn = false;
    try {
        localVersion = _fromPackageJson();
        shouldWarn = localVersion != null && globalVersion.compare(localVersion) > 0;
    }
    catch (e) {
        // eslint-disable-next-line no-console
        console.error(e);
        shouldWarn = true;
github angular / angular-cli / packages / angular_devkit / build_angular / src / dev-server / index.ts View on Github external
private _buildServerConfig(
    root: Path,
    options: DevServerBuilderSchema,
    browserOptions: NormalizedBrowserBuilderSchema,
  ) {
    const systemRoot = getSystemPath(root);
    if (options.host) {
      // Check that the host is either localhost or prints out a message.
      if (!/^127\.\d+\.\d+\.\d+/g.test(options.host) && options.host !== 'localhost') {
        this.context.logger.warn(tags.stripIndent`
          WARNING: This is a simple server for use in testing or debugging Angular applications
          locally. It hasn't been reviewed for security issues.

          Binding this server to an open connection can result in compromising your application or
          computer. Using a different host than the one passed to the "--host" flag might result in
          websocket connection issues. You might need to use "--disableHostCheck" if that's the
          case.
        `);
      }
    }
    if (options.disableHostCheck) {
      this.context.logger.warn(tags.oneLine`
github angular / angular-cli / packages / schematics / angular / library / index.ts View on Github external
validateProjectName(options.name);

    // If scoped project (i.e. "@foo/bar"), convert projectDir to "foo/bar".
    const projectName = options.name;
    const packageName = strings.dasherize(projectName);
    let scopeName = null;
    if (/^@.*\/.*/.test(options.name)) {
      const [scope, name] = options.name.split('/');
      scopeName = scope.replace(/^@/, '');
      options.name = name;
    }

    const workspace = await getWorkspace(host);
    const newProjectRoot = workspace.extensions.newProjectRoot as (string | undefined) || '';

    const scopeFolder = scopeName ? strings.dasherize(scopeName) + '/' : '';
    const folderName = `${scopeFolder}${strings.dasherize(options.name)}`;
    const projectRoot = join(normalize(newProjectRoot), folderName);
    const distRoot = `dist/${folderName}`;
    const sourceDir = `${projectRoot}/src/lib`;

    const templateSource = apply(url('./files'), [
      applyTemplates({
        ...strings,
        ...options,
        packageName,
        projectRoot,
        distRoot,
        relativePathToWorkspaceRoot: relativePathToWorkspaceRoot(projectRoot),
        prefix,
        angularLatestVersion: latestVersions.Angular.replace('~', '').replace('^', ''),
        tsLibLatestVersion: latestVersions.TsLib.replace('~', '').replace('^', ''),
github johandb / svg-drawing-tool / node_modules / @angular-devkit / build-angular / src / karma / index.js View on Github external
karmaOptions.singleRun = !options.watch;
            }
            // Convert browsers from a string to an array
            if (options.browsers) {
                karmaOptions.browsers = options.browsers.split(',');
            }
            if (options.reporters) {
                // Split along commas to make it more natural, and remove empty strings.
                const reporters = options.reporters
                    .reduce((acc, curr) => acc.concat(curr.split(/,/)), [])
                    .filter(x => !!x);
                if (reporters.length > 0) {
                    karmaOptions.reporters = reporters;
                }
            }
            const sourceRoot = builderConfig.sourceRoot && core_1.resolve(root, builderConfig.sourceRoot);
            karmaOptions.buildWebpack = {
                root: core_1.getSystemPath(root),
                projectRoot: core_1.getSystemPath(projectRoot),
                options,
                webpackConfig: this.buildWebpackConfig(root, projectRoot, sourceRoot, host, options),
                // Pass onto Karma to emit BuildEvents.
                successCb: () => obs.next({ success: true }),
                failureCb: () => obs.next({ success: false }),
                // Workaround for https://github.com/karma-runner/karma/issues/3154
                // When this workaround is removed, user projects need to be updated to use a Karma
                // version that has a fix for this issue.
                toJSON: () => { },
                logger: this.context.logger,
            };
            // TODO: inside the configs, always use the project root and not the workspace root.
            // Until then we pretend the app root is relative (``) but the same as `projectRoot`.
github just-jeb / electron-angular-native / custom-builders / src / custom-webpack / index.ts View on Github external
run(builderConfig: BuilderConfiguration): Observable {
    console.log('Hi');
    const options = builderConfig.options;
    const root = this.context.workspace.root;
    const projectRoot = resolve(root, builderConfig.root);
    const host = new virtualFs.AliasHost(this.context.host as virtualFs.Host);
    const webpackBuilder = new WebpackBuilder({ ...this.context, host });

    return of(null).pipe(
      concatMap(() => options.deleteOutputPath
        ? this._deleteOutputDir(root, normalize(options.outputPath), this.context.host)
        : of(null)),
      concatMap(() => addFileReplacements(root, host, options.fileReplacements)),
      concatMap(() => normalizeAssetPatterns(
        options.assets, host, root, projectRoot, builderConfig.sourceRoot)),
      // Replace the assets in options with the normalized version.
      tap((assetPatternObjects => options.assets = assetPatternObjects)),
      concatMap(() => {
        // Ensure Build Optimizer is only used with AOT.
        if (options.buildOptimizer && !options.aot) {
          throw new Error('The `--build-optimizer` option cannot be used without `--aot`.');
github angular / angular-cli / packages / angular_devkit / build_webpack / src / protractor / index_spec_big.ts View on Github external
describe('Protractor Target', () => {
  const devkitRoot = (global as any)._DevKitRoot; // tslint:disable-line:no-any
  const root = resolve(devkitRoot, 'tests/@angular_devkit/build_webpack/hello-world-app/');
  const builderPath = resolve(devkitRoot, 'packages/angular_devkit/build_webpack');
  const relativeBuilderPath = relative(root, builderPath);
  const host = new NodeJsSyncHost();

  const getWorkspace = (): Workspace => {
    const workspace = getDevServerWorkspace();
    workspace.projects.app.defaultTarget = 'protractor';
    workspace.projects.app.targets['protractor'] = {
      builder: `${relativeBuilderPath}:protractor`,
      options: {
        protractorConfig: '../protractor.conf.js',
        devServerTarget: 'app:devServer',
      },
    };

    return workspace;
  };

  it('runs', (done) => {
github angular / angular-cli / packages / schematics / angular / utility / find-module.ts View on Github external
export function buildRelativePath(from: string, to: string): string {
  from = normalize(from);
  to = normalize(to);

  // Convert to arrays.
  const fromParts = from.split('/');
  const toParts = to.split('/');

  // Remove file names (preserving destination)
  fromParts.pop();
  const toFileName = toParts.pop();

  const relativePath = relative(normalize(fromParts.join('/') || '/'),
   normalize(toParts.join('/') || '/'));
  let pathPrefix = '';

  // Set the path prefix for same dir or child dir, parent dir starts with `..`
  if (!relativePath) {
    pathPrefix = '.';
  } else if (!relativePath.startsWith('.')) {
    pathPrefix = `./`;
  }
  if (pathPrefix && !pathPrefix.endsWith('/')) {
    pathPrefix += '/';
  }

  return pathPrefix + (relativePath ? relativePath + '/' : '') + toFileName;
}
github manfredsteyer / angular-crud / angular-crud / src / schematics-angular-utils / find-module.ts View on Github external
export function buildRelativePath(from: string, to: string): string {
  from = normalize(from);
  to = normalize(to);

  // Convert to arrays.
  const fromParts = from.split('/');
  const toParts = to.split('/');

  // Remove file names (preserving destination)
  fromParts.pop();
  const toFileName = toParts.pop();

  const relativePath = relative(normalize(fromParts.join('/')), normalize(toParts.join('/')));
  let pathPrefix = '';

  // Set the path prefix for same dir or child dir, parent dir starts with `..`
  if (!relativePath) {
    pathPrefix = '.';
  } else if (!relativePath.startsWith('.')) {
    pathPrefix = `./`;
  }
  if (pathPrefix && !pathPrefix.endsWith('/')) {
    pathPrefix += '/';
  }

  return pathPrefix + (relativePath ? relativePath + '/' : '') + toFileName;
}
github NativeScript / nativescript-schematics / src / migrate-component / component-info-utils.ts View on Github external
if (tree.exists(componentPath)) {
      console.log(`${componentClassName} file found at: ${componentPath}`);
    } else {
      throw new SchematicsException(`Cannot locate Component ${componentClassName} at: ${componentPath}`);
    }
  } else {
    console.log(`Trying to deduct ${componentClassName} location following Angular best practices`);

    const fileName = `${dasherize(options.name)}.component.ts`;
    const app = join(projectSettings.sourceRoot, 'app');

    // search at src/app/file-name
    if (tree.exists(join(app, fileName))) {
      componentPath = join(app, fileName);
    } else if (tree.exists(join(app, dasherize(options.name), fileName))) {
      componentPath = join(app, dasherize(options.name), fileName);
    } else {
      throw new SchematicsException(`Couldn't find component's .ts file.
  You can use --component-path parameter to provide the path to the component.
  Hint. don't include src/app with --component-path`);
    }
  }

  return componentPath;
};
github NativeScript / nativescript-schematics / src / migrate-component / component-info-utils.ts View on Github external
componentPath = projectSettings.tsResolver(componentImportPath, modulePath);

    if (!componentPath.endsWith('.ts')) {
      componentPath = componentPath + '.ts';
    }

    if (tree.exists(componentPath)) {
      console.log(`${componentClassName} file found at: ${componentPath}`);
    } else {
      throw new SchematicsException(`Cannot locate Component ${componentClassName} at: ${componentPath}`);
    }
  } else {
    console.log(`Trying to deduct ${componentClassName} location following Angular best practices`);

    const fileName = `${dasherize(options.name)}.component.ts`;
    const app = join(projectSettings.sourceRoot, 'app');

    // search at src/app/file-name
    if (tree.exists(join(app, fileName))) {
      componentPath = join(app, fileName);
    } else if (tree.exists(join(app, dasherize(options.name), fileName))) {
      componentPath = join(app, dasherize(options.name), fileName);
    } else {
      throw new SchematicsException(`Couldn't find component's .ts file.
  You can use --component-path parameter to provide the path to the component.
  Hint. don't include src/app with --component-path`);
    }
  }

  return componentPath;
};