Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 10 additions & 43 deletions src/builders/build/builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import {
buildApplication,
} from "@angular/build";
import {
buildApplicationInternal,
normalizeDevServerOptions,
serveWithVite,
SourceFileCache,
Expand Down Expand Up @@ -46,7 +45,7 @@ import {
sharedMappingDirs,
syncNfFileWatcher,
} from "@softarc/native-federation/internal";
import { type Plugin, type PluginBuild } from "esbuild";
import { type PluginBuild } from "esbuild";
import { devHostInstancesPlugin } from "../../plugin/dev-host-instances-plugin.js";
import { withDiskCaseWorkspaceRoot } from "./../../utils/disk-case.js";
import { checkForInvalidImports } from "./../../utils/check-for-invalid-imports.js";
Expand All @@ -63,6 +62,7 @@ import { createAngularBuildAdapter } from "../../tools/esbuild/angular-esbuild-a
import { createSharedMappingsPlugin } from "../../tools/esbuild/shared-mappings-plugin.js";
import { getI18nConfig, translateFederationArtifacts } from "./i18n.js";
import { updateScriptTags } from "./update-index-html.js";
import { createInternalAngularBuilder } from "./internal-angular-builder.js";

const originalWrite = process.stderr.write.bind(process.stderr);

Expand All @@ -87,47 +87,6 @@ process.stderr.write = function (
return originalWrite(chunk, encodingOrCallback as BufferEncoding, callback);
};

const createInternalAngularBuilder =
(
externals: string[],
opts?: { instrumentForCoverage?: (filename: string) => boolean },
) =>
(
options: Parameters<typeof buildApplicationInternal>[0],
context: BuilderContext,
pluginsOrExtensions?:
| Plugin[]
| Parameters<typeof buildApplicationInternal>[2],
) => {
let extensions: Parameters<typeof buildApplicationInternal>[2];
if (pluginsOrExtensions && Array.isArray(pluginsOrExtensions)) {
extensions = {
codePlugins: pluginsOrExtensions,
};
} else {
extensions = pluginsOrExtensions as Parameters<
typeof buildApplicationInternal
>[2];
}

// serveWithVite fetches its own browserOptions independently, so ngBuilderOptions
// modifications don't reach here. Add NF externals to externalDependencies so
// Angular routes them to optimizeDeps.exclude, preventing Vite from trying to
// pre-bundle packages that include native .node binaries.
options.externalDependencies = [
...(options.externalDependencies ?? []),
...externals,
];

if (opts?.instrumentForCoverage) {
options.instrumentForCoverage = opts.instrumentForCoverage;
}

// Todo: share cache with Angular builder: https://github.com/angular/angular-cli/pull/32527
// options.codeBundleCache = nfOptions.federationCache.bundlerCache;
return buildApplicationInternal(options, context, extensions);
};

export async function* runBuilder(
nfBuilderOptions: NfBuilderSchema & NfInternalOptions,
builderContext: BuilderContext,
Expand Down Expand Up @@ -218,6 +177,13 @@ export async function* runBuilder(
ngBuilderOptions.outputPath = nfBuilderOptions.outputPath;
}

if (nfBuilderOptions.define) {
ngBuilderOptions.define = {
...ngBuilderOptions.define,
...nfBuilderOptions.define,
};
}

const declaresTsConfig =
!!nfBuilderOptions.tsConfig && nfBuilderOptions.tsConfig.length > 0;

Expand Down Expand Up @@ -557,6 +523,7 @@ export async function* runBuilder(
appBuilderName,
createInternalAngularBuilder(externals, {
instrumentForCoverage: nfBuilderOptions.instrumentForCoverage,
define: nfBuilderOptions.define,
}),
context,
nfBuilderOptions.skipHtmlTransform
Expand Down
47 changes: 47 additions & 0 deletions src/builders/build/internal-angular-builder.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { buildApplicationInternal } from "@angular/build/private";
import type { BuilderContext } from "@angular-devkit/architect";

import { createInternalAngularBuilder } from "./internal-angular-builder.js";

vi.mock("@angular/build/private", () => ({
buildApplicationInternal: vi.fn(),
}));

type Options = Parameters<typeof buildApplicationInternal>[0];

function run(
options: Partial<Options>,
opts?: Parameters<typeof createInternalAngularBuilder>[1],
) {
createInternalAngularBuilder(["@angular/core"], opts)(
options as Options,
{} as BuilderContext,
);
return vi.mocked(buildApplicationInternal).mock.calls.at(-1)![0];
}

describe("createInternalAngularBuilder", () => {
beforeEach(() => vi.mocked(buildApplicationInternal).mockClear());

it("appends the federation externals", () => {
expect(run({ externalDependencies: ["fs"] }).externalDependencies).toEqual([
"fs",
"@angular/core",
]);
});

// #129: serveWithVite reads the build target's options itself, so the builder's define
// must be merged here or `serve --define` never reaches the main bundle.
it("merges the builder define over the target define", () => {
const options = run(
{ define: { BUILD_ID: "'target'", KEEP: "true" } },
{ define: { BUILD_ID: "'cli'" } },
);

expect(options.define).toEqual({ BUILD_ID: "'cli'", KEEP: "true" });
});

it("leaves the target define alone when the builder sets none", () => {
expect(run({ define: { KEEP: "true" } }).define).toEqual({ KEEP: "true" });
});
});
50 changes: 50 additions & 0 deletions src/builders/build/internal-angular-builder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { buildApplicationInternal } from "@angular/build/private";
import { type BuilderContext } from "@angular-devkit/architect";
import { type Plugin } from "esbuild";

export const createInternalAngularBuilder =
(
externals: string[],
opts?: {
instrumentForCoverage?: (filename: string) => boolean;
define?: Record<string, string>;
},
) =>
(
options: Parameters<typeof buildApplicationInternal>[0],
context: BuilderContext,
pluginsOrExtensions?:
Plugin[] | Parameters<typeof buildApplicationInternal>[2],
) => {
let extensions: Parameters<typeof buildApplicationInternal>[2];
if (pluginsOrExtensions && Array.isArray(pluginsOrExtensions)) {
extensions = {
codePlugins: pluginsOrExtensions,
};
} else {
extensions = pluginsOrExtensions as Parameters<
typeof buildApplicationInternal
>[2];
}

// serveWithVite fetches its own browserOptions independently, so ngBuilderOptions
// modifications don't reach here. Add NF externals to externalDependencies so
// Angular routes them to optimizeDeps.exclude, preventing Vite from trying to
// pre-bundle packages that include native .node binaries.
options.externalDependencies = [
...(options.externalDependencies ?? []),
...externals,
];

if (opts?.instrumentForCoverage) {
options.instrumentForCoverage = opts.instrumentForCoverage;
}

if (opts?.define) {
options.define = { ...options.define, ...opts.define };
}

// Todo: share cache with Angular builder: https://github.com/angular/angular-cli/pull/32527
// options.codeBundleCache = nfOptions.federationCache.bundlerCache;
return buildApplicationInternal(options, context, extensions);
};
1 change: 1 addition & 0 deletions src/builders/build/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export interface NfBuilderSchema extends JsonObject {
esmsInitOptions: ESMSInitOptions;
baseHref?: string;
outputPath?: string;
define?: Record<string, string>;
projectName?: string;
ssr: boolean;
tsConfig?: string;
Expand Down
5 changes: 5 additions & 0 deletions src/builders/build/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,11 @@
"outputPath": {
"type": "string"
},
"define": {
"type": "object",
"additionalProperties": { "type": "string" },
"description": "Global identifiers to replace at build time, merged over the Angular target's own 'define'. String values must be put in quotes."
},
"esmsInitOptions": {
"type": "object",
"description": "Options for esms-module-shims https://github.com/guybedford/es-module-shims?tab=readme-ov-file#init-options",
Expand Down
21 changes: 21 additions & 0 deletions src/tools/esbuild/angular-bundler.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,4 +145,25 @@ describe('createAngularEsbuildContext', () => {

expect(lastBuildOptions().entryPoints).toEqual([{ in: absolute, out: 'ui' }]);
});

// #129: exposed modules left user defines unreplaced, throwing a ReferenceError in the host.
// Angular's own flags win over user defines, mirroring the application builder.
it('applies the builder define, keeping the Angular flags on top', async () => {
await createAngularEsbuildContext(
makeOptions({
builderOptions: {
optimization: false,
sourceMap: false,
define: { BUILD_ID: "'abc'", ngJitMode: 'true' },
},
} as unknown as Partial<NormalizedContextOptions>),
'mapping-or-exposed'
);

expect(lastBuildOptions().define).toEqual({
BUILD_ID: "'abc'",
ngDevMode: 'false',
ngJitMode: 'false',
});
});
});
1 change: 1 addition & 0 deletions src/tools/esbuild/angular-bundler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ export async function createAngularEsbuildContext(
logLimit: 0,
plugins: [compilerPlugin, commonjsPlugin(), ...customPlugins],
define: {
...builderOptions.define,
...(dev ? {} : { ngDevMode: 'false' }),
ngJitMode: 'false',
},
Expand Down
Loading