Skip to content

Commit

Permalink
fix(@angular-devkit/build-angular): attempt relative global script re…
Browse files Browse the repository at this point in the history
…ad first in esbuild builder

When using a global script (`scripts` option) with the esbuild-based browser application builder,
an attempt to read the script as a relative path from the workspace root will be performed first.
This avoids the need to perform a potentially expensive module resolution attempt for files that
are directly available and also ensures the relative paths are given priority over any potential
modules with the same name. This matches prior behavior that also preferred relative paths.
  • Loading branch information
clydin authored and angular-robot[bot] committed May 15, 2023
1 parent ac95732 commit 141d74d
Showing 1 changed file with 28 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import type { BuildOptions } from 'esbuild';
import MagicString, { Bundle } from 'magic-string';
import assert from 'node:assert';
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { assertIsError } from '../../utils/error';
import { NormalizedBrowserOptions } from './options';
import { createSourcemapIngorelistPlugin } from './sourcemap-ignorelist-plugin';

Expand Down Expand Up @@ -96,23 +98,36 @@ export function createGlobalScriptsBundleOptions(
// Global scripts are concatenated using magic-string instead of bundled via esbuild.
const bundleContent = new Bundle();
for (const filename of files) {
const resolveResult = await build.resolve(filename, {
kind: 'entry-point',
resolveDir: workspaceRoot,
});
let fileContent;
try {
// Attempt to read as a relative path from the workspace root
fileContent = await readFile(path.join(workspaceRoot, filename), 'utf-8');
} catch (e) {
assertIsError(e);
if (e.code !== 'ENOENT') {
throw e;
}

if (resolveResult.errors.length) {
// Remove resolution failure notes about marking as external since it doesn't apply
// to global scripts.
resolveResult.errors.forEach((error) => (error.notes = []));
// If not found attempt to resolve as a module specifier
const resolveResult = await build.resolve(filename, {
kind: 'entry-point',
resolveDir: workspaceRoot,
});

return {
errors: resolveResult.errors,
warnings: resolveResult.warnings,
};
if (resolveResult.errors.length) {
// Remove resolution failure notes about marking as external since it doesn't apply
// to global scripts.
resolveResult.errors.forEach((error) => (error.notes = []));

return {
errors: resolveResult.errors,
warnings: resolveResult.warnings,
};
}

fileContent = await readFile(resolveResult.path, 'utf-8');
}

const fileContent = await readFile(resolveResult.path, 'utf-8');
bundleContent.addSource(new MagicString(fileContent, { filename }));
}

Expand Down

0 comments on commit 141d74d

Please sign in to comment.