Skip to content

Commit

Permalink
refactor: reduce direct babel dependencies
Browse files Browse the repository at this point in the history
The `@babel/core` package provides the functionality of multiple other babel packages
without the need to directly depend or import the other babel packages. Since the
`@babel/core` package is already used and imported in the locations that previously
used the other babel packages, an overall reduction in both imports and dependencies
is possible. Six babel related packages were able to be removed from the root `package.json`
and one (also present in the aforementioned six) was removed as a dependency from the
`@angular/localize` package.

The following packages were removed:
  • Loading branch information
clydin committed Dec 5, 2023
1 parent 1e3bcfe commit 092d2f4
Show file tree
Hide file tree
Showing 19 changed files with 40 additions and 114 deletions.
3 changes: 1 addition & 2 deletions goldens/public-api/localize/tools/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,12 @@

/// <reference types="@angular/compiler-cli/private/babel" />
/// <reference types="@types/babel__core" />
/// <reference types="@types/babel__traverse" />

import { AbsoluteFsPath } from '@angular/compiler-cli/private/localize';
import { Element as Element_2 } from '@angular/compiler';
import { Logger } from '@angular/compiler-cli/private/localize';
import { MessageId } from '@angular/localize';
import { NodePath } from '@babel/traverse';
import { NodePath } from '@babel/core';
import { ParseError } from '@angular/compiler';
import { PathManipulation } from '@angular/compiler-cli/private/localize';
import { PluginObj } from '@babel/core';
Expand Down
6 changes: 0 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,7 @@
"@babel/core": "7.23.2",
"@babel/generator": "7.23.0",
"@babel/helper-replace-supers": "7.22.20",
"@babel/parser": "7.23.0",
"@babel/preset-env": "7.23.2",
"@babel/template": "7.22.15",
"@babel/traverse": "7.23.2",
"@babel/types": "7.23.0",
"@bazel/concatjs": "5.8.1",
"@bazel/esbuild": "5.8.1",
"@bazel/jasmine": "5.8.1",
Expand All @@ -79,8 +75,6 @@
"@types/angular": "^1.6.47",
"@types/babel__core": "7.20.2",
"@types/babel__generator": "7.6.5",
"@types/babel__template": "7.4.2",
"@types/babel__traverse": "7.20.2",
"@types/bluebird": "^3.5.27",
"@types/chrome": "^0.0.248",
"@types/convert-source-map": "^2.0.0",
Expand Down
1 change: 0 additions & 1 deletion packages/compiler-cli/linker/babel/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,5 @@ ts_library(
"//packages/compiler-cli/src/ngtsc/translator",
"@npm//@babel/core",
"@npm//@types/babel__core",
"@npm//@types/babel__traverse",
],
)
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {types as t} from '@babel/core';
import {NodePath, Scope} from '@babel/traverse';
import {NodePath, types as t} from '@babel/core';

import {DeclarationScope} from '../../../linker';

Expand All @@ -25,7 +24,7 @@ export class BabelDeclarationScope implements DeclarationScope<ConstantScopePath
*
* @param declarationScope the Babel scope containing the declaration call expression.
*/
constructor(private declarationScope: Scope) {}
constructor(private declarationScope: NodePath['scope']) {}

/**
* Compute the Babel `NodePath` that can be used to reference the lexical scope where any
Expand Down
13 changes: 6 additions & 7 deletions packages/compiler-cli/linker/babel/src/es2015_linker_plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/

import {BabelFile, PluginObj, types as t} from '@babel/core';
import {NodePath} from '@babel/traverse';
import {BabelFile, NodePath, PluginObj, types as t} from '@babel/core';

import {FileLinker, isFatalLinkerError, LinkerEnvironment} from '../../../linker';

Expand All @@ -33,11 +32,11 @@ export function createEs2015LinkerPlugin({fileSystem, logger, ...options}: Linke
/**
* Create a new `FileLinker` as we enter each file (`t.Program` in Babel).
*/
enter(path: NodePath<t.Program>): void {
enter(_, state): void {
assertNull(fileLinker);
// Babel can be configured with a `filename` or `relativeFilename` (or both, or neither) -
// possibly relative to the optional `cwd` path.
const file = path.hub.file;
const file = state.file;
const filename = file.opts.filename ?? file.opts.filenameRelative;
if (!filename) {
throw new Error(
Expand Down Expand Up @@ -67,7 +66,7 @@ export function createEs2015LinkerPlugin({fileSystem, logger, ...options}: Linke
* Test each call expression to see if it is a partial declaration; it if is then replace it
* with the results of linking the declaration.
*/
CallExpression(call: NodePath<t.CallExpression>): void {
CallExpression(call: NodePath<t.CallExpression>, state): void {
if (fileLinker === null) {
// Any statements that are inserted upon program exit will be visited outside of an active
// linker context. These call expressions are known not to contain partial declarations,
Expand All @@ -91,7 +90,7 @@ export function createEs2015LinkerPlugin({fileSystem, logger, ...options}: Linke
call.replaceWith(replacement);
} catch (e) {
const node = isFatalLinkerError(e) ? e.node as t.Node : call.node;
throw buildCodeFrameError(call.hub.file, (e as Error).message, node);
throw buildCodeFrameError(state.file, (e as Error).message, node);
}
}
}
Expand Down Expand Up @@ -176,6 +175,6 @@ function assertNotNull<T>(obj: T|null): asserts obj is T {
*/
function buildCodeFrameError(file: BabelFile, message: string, node: t.Node): string {
const filename = file.opts.filename || '(unknown file)';
const error = file.buildCodeFrameError(node, message);
const error = file.hub.buildError(node, message);
return `${filename}: ${error.message}`;
}
5 changes: 0 additions & 5 deletions packages/compiler-cli/linker/babel/test/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,8 @@ ts_library(
"//packages/compiler-cli/src/ngtsc/logging/testing",
"//packages/compiler-cli/src/ngtsc/translator",
"@npm//@babel/generator",
"@npm//@babel/parser",
"@npm//@babel/template",
"@npm//@babel/traverse",
"@npm//@types/babel__core",
"@npm//@types/babel__generator",
"@npm//@types/babel__template",
"@npm//@types/babel__traverse",
],
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,8 @@
* found in the LICENSE file at https://angular.io/license
*/
import {leadingComment} from '@angular/compiler';
import {types as t} from '@babel/core';
import {template, types as t} from '@babel/core';
import _generate from '@babel/generator';
import _template from '@babel/template';

import {BabelAstFactory} from '../../src/ast/babel_ast_factory';

Expand All @@ -18,8 +17,8 @@ const generate = (_generate as any)['default'] as typeof _generate;

// Exposes shorthands for the `expression` and `statement`
// methods exposed by `@babel/template`.
const expression = _template.expression;
const statement = _template.statement;
const expression = template.expression;
const statement = template.statement;

describe('BabelAstFactory', () => {
let factory: BabelAstFactory;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,10 @@
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {types as t} from '@babel/core';
import parser from '@babel/parser';
import _template from '@babel/template';
import {parse, template, types as t} from '@babel/core';

import {BabelAstHost} from '../../src/ast/babel_ast_host';

// Babel is a CJS package and misuses the `default` named binding:
// https://github.com/babel/babel/issues/15269.
const template = (_template as any)['default'] as typeof _template;

describe('BabelAstHost', () => {
let host: BabelAstHost;
beforeEach(() => host = new BabelAstHost());
Expand Down Expand Up @@ -331,8 +325,8 @@ describe('BabelAstHost', () => {

describe('getRange()', () => {
it('should extract the range from the expression', () => {
const file = parser.parse('// preamble\nx = \'moo\';');
const stmt = file.program.body[0] as t.Statement;
const file = parse('// preamble\nx = \'moo\';');
const stmt = file!.program.body[0] as t.Statement;
assertExpressionStatement(stmt);
assertAssignmentExpression(stmt.expression);
expect(host.getRange(stmt.expression.right))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,14 @@
* found in the LICENSE file at https://angular.io/license
*/

import {types as t} from '@babel/core';
import parser from '@babel/parser';
import _traverse, {NodePath} from '@babel/traverse';
import {NodePath, parse, traverse, types as t} from '@babel/core';

import {BabelDeclarationScope} from '../src/babel_declaration_scope';

// Babel is a CJS package and misuses the `default` named binding:
// https://github.com/babel/babel/issues/15269.
const traverse = (_traverse as any)['default'] as typeof _traverse;

describe('BabelDeclarationScope', () => {
describe('getConstantScopeRef()', () => {
it('should return a path to the ES module where the expression was imported', () => {
const ast = parser.parse(
const ast = parse(
[
'import * as core from \'@angular/core\';',
'function foo() {',
Expand All @@ -35,7 +29,7 @@ describe('BabelDeclarationScope', () => {
});

it('should return a path to the ES Module where the expression is declared', () => {
const ast = parser.parse(
const ast = parse(
[
'var core;',
'export function foo() {',
Expand All @@ -51,7 +45,7 @@ describe('BabelDeclarationScope', () => {
});

it('should return null if the file is not an ES module', () => {
const ast = parser.parse(
const ast = parse(
[
'var core;',
'function foo() {',
Expand All @@ -66,7 +60,7 @@ describe('BabelDeclarationScope', () => {
});

it('should return the IIFE factory function where the expression is a parameter', () => {
const ast = parser.parse(
const ast = parse(
[
'var core;',
'(function(core) {',
Expand Down
20 changes: 1 addition & 19 deletions packages/compiler-cli/private/babel.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,6 @@
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { BabelFile, types as t } from '@babel/core';

/**
* Augment some Babel types to add symbols that we rely on, but are not included in the Babel typings.
*/

declare module '@babel/traverse' {
interface Hub {
file: BabelFile;
}
}

declare module '@babel/core' {
interface BabelFile {
buildCodeFrameError(node: t.Node, message: string): Error;
}
}

// The following modules are declared to work around a limitation in tsc_wrapped's `strict_deps`
// check. Since Babel uses scoped packages, the corresponding lookup for declaration files in the
Expand All @@ -37,6 +20,5 @@ declare module '@babel/core' {
// that is not governed by Bazel, and therefore not expected by the `strict_deps` rule.
// Declaring the modules here allows `strict_deps` to always find a declaration of the modules
// in an input file to the compilation, therefore accepting the module import.
declare module '@babel/core' {}
declare module '@babel/generator' {}
declare module '@babel/template' {}
declare module '@babel/parser' {}
1 change: 0 additions & 1 deletion packages/localize/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@
"dependencies": {
"@babel/core": "7.23.2",
"@types/babel__core": "7.20.2",
"@types/babel__traverse": "7.20.2",
"fast-glob": "3.3.1",
"yargs": "^17.2.1"
},
Expand Down
1 change: 0 additions & 1 deletion packages/localize/tools/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ ts_library(
"//packages/localize",
"@npm//@babel/core",
"@npm//@types/babel__core",
"@npm//@types/babel__traverse",
"@npm//@types/node",
"@npm//@types/yargs",
"@npm//fast-glob",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export function makeEs5ExtractPlugin(
fs: PathManipulation, messages: ɵParsedMessage[], localizeName = '$localize'): PluginObj {
return {
visitor: {
CallExpression(callPath: NodePath<t.CallExpression>) {
CallExpression(callPath: NodePath<t.CallExpression>, state) {
try {
const calleePath = callPath.get('callee');
if (isNamedIdentifier(calleePath, localizeName) && isGlobalIdentifier(calleePath)) {
Expand All @@ -34,7 +34,7 @@ export function makeEs5ExtractPlugin(
// If we get a BabelParseError here then something went wrong with Babel itself
// since there must be something wrong with the structure of the AST generated
// by Babel parsing a TaggedTemplateExpression.
throw buildCodeFrameError(fs, callPath, e);
throw buildCodeFrameError(fs, callPath, state.file, e);
} else {
throw e;
}
Expand Down
23 changes: 8 additions & 15 deletions packages/localize/tools/src/source_file_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@
*/
import {AbsoluteFsPath, getFileSystem, PathManipulation} from '@angular/compiler-cli/private/localize';
import {ɵisMissingTranslationError, ɵmakeTemplateObject, ɵParsedTranslation, ɵSourceLocation, ɵtranslate} from '@angular/localize';
import {types as t} from '@babel/core';
import {NodePath} from '@babel/traverse';
import {BabelFile, NodePath, types as t} from '@babel/core';

import {DiagnosticHandlingStrategy, Diagnostics} from './diagnostics';

Expand Down Expand Up @@ -404,19 +403,19 @@ export function isBabelParseError(e: any): e is BabelParseError {
}

export function buildCodeFrameError(
fs: PathManipulation, path: NodePath, e: BabelParseError): string {
let filename = path.hub.file.opts.filename;
fs: PathManipulation, path: NodePath, file: BabelFile, e: BabelParseError): string {
let filename = file.opts.filename;
if (filename) {
filename = fs.resolve(filename);
let cwd = path.hub.file.opts.cwd;
let cwd = file.opts.cwd;
if (cwd) {
cwd = fs.resolve(cwd);
filename = fs.relative(cwd, filename);
}
} else {
filename = '(unknown file)';
}
const message = path.hub.file.buildCodeFrameError(e.node, e.message).message;
const {message} = file.hub.buildError(e.node, e.message);
return `${filename}: ${message}`;
}

Expand All @@ -435,7 +434,7 @@ export function getLocation(
start: getLineAndColumn(startLocation.start),
end: getLineAndColumn(endLocation.end),
file,
text: getText(startPath),
text: startPath.getSource() || undefined,
};
}

Expand All @@ -447,7 +446,8 @@ export function serializeLocationPosition(location: ɵSourceLocation): string {
}

function getFileFromPath(fs: PathManipulation, path: NodePath|undefined): AbsoluteFsPath|null {
const opts = path?.hub.file.opts;
// The file field is not guaranteed to be present for all node paths
const opts = (path?.hub as {file?: BabelFile}).file?.opts;
const filename = opts?.filename;
if (!filename || !opts.cwd) {
return null;
Expand All @@ -462,10 +462,3 @@ function getLineAndColumn(loc: {line: number, column: number}): {line: number, c
// Note we want 0-based line numbers but Babel returns 1-based.
return {line: loc.line - 1, column: loc.column};
}

function getText(path: NodePath): string|undefined {
if (path.node.start == null || path.node.end == null) {
return undefined;
}
return path.hub.file.code.substring(path.node.start, path.node.end);
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export function makeEs2015TranslatePlugin(
fs: PathManipulation = getFileSystem()): PluginObj {
return {
visitor: {
TaggedTemplateExpression(path: NodePath<t.TaggedTemplateExpression>) {
TaggedTemplateExpression(path: NodePath<t.TaggedTemplateExpression>, state) {
try {
const tag = path.get('tag');
if (isLocalize(tag, localizeName)) {
Expand All @@ -40,7 +40,7 @@ export function makeEs2015TranslatePlugin(
// If we get a BabelParseError here then something went wrong with Babel itself
// since there must be something wrong with the structure of the AST generated
// by Babel parsing a TaggedTemplateExpression.
throw buildCodeFrameError(fs, path, e);
throw buildCodeFrameError(fs, path, state.file, e);
} else {
throw e;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export function makeEs5TranslatePlugin(
fs: PathManipulation = getFileSystem()): PluginObj {
return {
visitor: {
CallExpression(callPath: NodePath<t.CallExpression>) {
CallExpression(callPath: NodePath<t.CallExpression>, state) {
try {
const calleePath = callPath.get('callee');
if (isLocalize(calleePath, localizeName)) {
Expand All @@ -36,7 +36,7 @@ export function makeEs5TranslatePlugin(
}
} catch (e) {
if (isBabelParseError(e)) {
diagnostics.error(buildCodeFrameError(fs, callPath, e));
diagnostics.error(buildCodeFrameError(fs, callPath, state.file, e));
} else {
throw e;
}
Expand Down
Loading

0 comments on commit 092d2f4

Please sign in to comment.