Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reduce usage of require calls in @angular/cli package #21174

Merged
merged 3 commits into from Jun 22, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 2 additions & 3 deletions packages/angular/cli/commands/new-impl.ts
Expand Up @@ -8,6 +8,7 @@

import { Arguments } from '../models/interface';
import { SchematicCommand } from '../models/schematic-command';
import { VERSION } from '../models/version';
import { Schema as NewCommandSchema } from './new';

export class NewCommand extends SchematicCommand<NewCommandSchema> {
Expand All @@ -22,9 +23,7 @@ export class NewCommand extends SchematicCommand<NewCommandSchema> {

public async run(options: NewCommandSchema & Arguments) {
// Register the version of the CLI in the registry.
const packageJson = require('../package.json');
const version = packageJson.version;

const version = VERSION.full;
this._workflow.registry.addSmartDefaultProvider('ng-cli-version', () => version);

return this.runSchematic({
Expand Down
3 changes: 2 additions & 1 deletion packages/angular/cli/commands/update-impl.ts
Expand Up @@ -16,6 +16,7 @@ import { PackageManager } from '../lib/config/workspace-schema';
import { Command } from '../models/command';
import { Arguments } from '../models/interface';
import { SchematicEngineHost } from '../models/schematic-engine-host';
import { VERSION } from '../models/version';
import { colors } from '../utilities/color';
import { installAllPackages, runTempPackageBin } from '../utilities/install-package';
import { writeErrorToLogFile } from '../utilities/log-file';
Expand Down Expand Up @@ -860,7 +861,7 @@ export class UpdateCommand extends Command<UpdateCommandSchema> {
* @returns `true` when the installed version is older.
*/
private async checkCLILatestVersion(verbose = false, next = false): Promise<boolean> {
const { version: installedCLIVersion } = require('../package.json');
const installedCLIVersion = VERSION.full;

const LatestCLIManifest = await fetchPackageManifest(
`@angular/cli@${next ? 'next' : 'latest'}`,
Expand Down
48 changes: 8 additions & 40 deletions packages/angular/cli/lib/init.ts
Expand Up @@ -8,48 +8,13 @@

import 'symbol-observable';
// symbol polyfill must go first
import * as fs from 'fs';
import { promises as fs } from 'fs';
import * as path from 'path';
import { SemVer } from 'semver';
import { VERSION } from '../models/version';
import { colors } from '../utilities/color';
import { isWarningEnabled } from '../utilities/config';

// Check if we need to profile this CLI run.
clydin marked this conversation as resolved.
Show resolved Hide resolved
if (process.env['NG_CLI_PROFILING']) {
let profiler: {
startProfiling: (name?: string, recsamples?: boolean) => void;
stopProfiling: (name?: string) => unknown;
};
try {
profiler = require('v8-profiler-node8'); // eslint-disable-line import/no-extraneous-dependencies
} catch (err) {
throw new Error(
`Could not require 'v8-profiler-node8'. You must install it separetely with ` +
`'npm install v8-profiler-node8 --no-save'.\n\nOriginal error:\n\n${err}`,
);
}

profiler.startProfiling();

const exitHandler = (options: { cleanup?: boolean; exit?: boolean }) => {
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 }));
}

(async () => {
/**
* Disable Browserslist old data warning as otherwise with every release we'd need to update this dependency
Expand Down Expand Up @@ -80,14 +45,17 @@ if (process.env['NG_CLI_PROFILING']) {
const projectLocalCli = require.resolve('@angular/cli', { paths: [process.cwd()] });
cli = await import(projectLocalCli);

const globalVersion = new SemVer(require('../package.json').version);
const globalVersion = new SemVer(VERSION.full);

// Older versions might not have the VERSION export
let localVersion = cli.VERSION?.full;
if (!localVersion) {
try {
localVersion = require(path.join(path.dirname(projectLocalCli), '../../package.json'))
.version;
const localPackageJson = await fs.readFile(
path.join(path.dirname(projectLocalCli), '../../package.json'),
'utf-8',
);
localVersion = (JSON.parse(localPackageJson) as { version: string }).version;
} catch (error) {
// eslint-disable-next-line no-console
console.error('Version mismatch check skipped. Unable to retrieve local version: ' + error);
Expand Down
3 changes: 2 additions & 1 deletion packages/angular/cli/models/analytics.ts
Expand Up @@ -10,6 +10,7 @@ import { json, tags } from '@angular-devkit/core';
import debug from 'debug';
import * as inquirer from 'inquirer';
import { v4 as uuidV4 } from 'uuid';
import { VERSION } from '../models/version';
import { colors } from '../utilities/color';
import { getWorkspace, getWorkspaceRaw } from '../utilities/config';
import { isTTY } from '../utilities/tty';
Expand All @@ -27,7 +28,7 @@ export const AnalyticsProperties = {
return _defaultAngularCliPropertyCache;
}

const v = require('../package.json').version;
const v = VERSION.full;

// The logic is if it's a full version then we should use the prod GA property.
if (/^\d+\.\d+\.\d+$/.test(v) && v !== '0.0.0') {
Expand Down
4 changes: 2 additions & 2 deletions packages/angular/cli/models/schematic-engine-host.ts
Expand Up @@ -10,6 +10,7 @@ import { RuleFactory, SchematicsException, Tree } from '@angular-devkit/schemati
import { NodeModulesEngineHost } from '@angular-devkit/schematics/tools';
import { readFileSync } from 'fs';
import { parse as parseJson } from 'jsonc-parser';
import nodeModule from 'module';
import { dirname, resolve } from 'path';
import { Script } from 'vm';

Expand Down Expand Up @@ -120,8 +121,7 @@ function wrap(
moduleCache: Map<string, unknown>,
exportName?: string,
): () => unknown {
const { createRequire } = require('module');
const scopedRequire = createRequire(schematicFile);
const scopedRequire = nodeModule.createRequire(schematicFile);

const customRequire = function (id: string) {
if (legacyModules[id]) {
Expand Down