Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Draft
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
feat(@schematics/angular): Applications are zoneless by default
This change updates applications to omit the ZoneJS dependency by
default. It depends on angular/angular#63382,
which allows us to also exclude the `provideZonelessChangeDetection`
provider.

This change also includes the addition of `provideZoneChangeDetection`
in the `initTestEnvironment` when ZoneJS is detected in the
configuration (either on window or in the polyfills).
  • Loading branch information
atscott committed Sep 9, 2025
commit 1a2767a0b1eaf765689a7cb3808c9d7ae69fd874
Original file line number Diff line number Diff line change
Expand Up @@ -436,14 +436,18 @@ async function initializeApplication(
externalDependencies: options.externalDependencies,
};

const usesZoneJS = buildOptions.polyfills.includes('zone.js');
const virtualTestBedInit = createVirtualModulePlugin({
namespace: 'angular:test-bed-init',
loadContent: async () => {
const contents: string[] = [
// Initialize the Angular testing environment
`import { NgModule${usesZoneJS ? ', provideZoneChangeDetection' : ''} } from '@angular/core';`,
`import { getTestBed } from '@angular/core/testing';`,
`import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';`,
`getTestBed().initTestEnvironment(BrowserTestingModule, platformBrowserTesting(), {`,
`@NgModule({ providers: [${usesZoneJS ? 'provideZoneChangeDetection(), ' : ''}], })`,
`export class TestModule {}`,
`getTestBed().initTestEnvironment([BrowserTestingModule, TestModule], platformBrowserTesting(), {`,
` errorOnUnknownElements: true,`,
` errorOnUnknownProperties: true,`,
'});',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,14 @@
import { NormalizedUnitTestBuilderOptions, injectTestingPolyfills } from '../../options';
import { findTests, getTestEntrypoints } from '../../test-discovery';
import { RunnerOptions } from '../api';
import { u } from 'tar';

Check failure on line 16 in packages/angular/build/src/builders/unit-test/runners/vitest/build-options.ts

View workflow job for this annotation

GitHub Actions / lint

`tar` import should occur before import of `../../../../utils/path`

function createTestBedInitVirtualFile(
providersFile: string | undefined,
projectSourceRoot: string,
polyfills: string[] = [],
): string {
const usesZoneJS = polyfills.includes('zone.js');
let providersImport = 'const providers = [];';
if (providersFile) {
const relativePath = path.relative(projectSourceRoot, providersFile);
Expand All @@ -28,15 +31,15 @@

return `
// Initialize the Angular testing environment
import { NgModule } from '@angular/core';
import { NgModule${usesZoneJS ? ', provideZoneChangeDetection' : ''} } from '@angular/core';
import { getTestBed, ɵgetCleanupHook as getCleanupHook } from '@angular/core/testing';
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
${providersImport}
// Same as https://github.com/angular/angular/blob/05a03d3f975771bb59c7eefd37c01fa127ee2229/packages/core/testing/srcs/test_hooks.ts#L21-L29
beforeEach(getCleanupHook(false));
afterEach(getCleanupHook(true));
@NgModule({
providers,
providers: [${usesZoneJS ? 'provideZoneChangeDetection(), ' : ''}...providers],
})
export class TestModule {}
getTestBed().initTestEnvironment([BrowserTestingModule, TestModule], platformBrowserTesting(), {
Expand Down Expand Up @@ -113,7 +116,11 @@

buildOptions.polyfills = injectTestingPolyfills(buildOptions.polyfills);

const testBedInitContents = createTestBedInitVirtualFile(providersFile, projectSourceRoot);
const testBedInitContents = createTestBedInitVirtualFile(
providersFile,
projectSourceRoot,
buildOptions.polyfills,
);

return {
buildOptions,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,16 @@
// TODO(dgp1130): These imports likely don't resolve in stricter package environments like `pnpm`, since they are resolved relative to
// `@angular-devkit/build-angular` rather than the user's workspace. Should look into virtual modules to support those use cases.

import { provideZoneChangeDetection, NgModule } from '@angular/core';
import { getTestBed } from '@angular/core/testing';
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';

getTestBed().initTestEnvironment(BrowserTestingModule, platformBrowserTesting(), {
@NgModule({
providers: [typeof window.Zone !== 'undefined' ? provideZoneChangeDetection() : []],
})
class TestModule {}

getTestBed().initTestEnvironment([BrowserTestingModule, TestModule], platformBrowserTesting(), {
errorOnUnknownElements: true,
errorOnUnknownProperties: true,
});
Original file line number Diff line number Diff line change
Expand Up @@ -149,14 +149,18 @@ async function initializeBrowser(
return [karma, (await webpackConfigurationTransformer?.(config)) ?? config];
}

function getBuiltInMainFile(): string {
function getBuiltInMainFile(includeZoneProvider = false): string {
const content = Buffer.from(
`
import { NgModule${includeZoneProvider ? ', provideZoneChangeDetection' : ''} } from '@angular/core';
import { getTestBed } from '@angular/core/testing';
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';

@NgModule({providers: [${includeZoneProvider ? 'provideZoneChangeDetection(), ' : ''}]})
export class TestModule {}

// Initialize the Angular testing environment.
getTestBed().initTestEnvironment(BrowserTestingModule, platformBrowserTesting(), {
getTestBed().initTestEnvironment([BrowserTestingModule, TestModule], platformBrowserTesting(), {
errorOnUnknownElements: true,
errorOnUnknownProperties: true
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
* found in the LICENSE file at https://angular.dev/license
*/

import { NgModule } from '@angular/core';
import { getTestBed } from '@angular/core/testing';
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
import {
Expand Down Expand Up @@ -63,8 +64,13 @@ export async function runJasmineTests(jasmineEnv) {
// eslint-disable-next-line no-undef
jasmine.DEFAULT_TIMEOUT_INTERVAL = config.defaultTimeoutInterval;

@NgModule({
providers: [typeof window.Zone !== 'undefined' ? provideZoneChangeDetection() : []],
})
class TestModule {}

// Initialize `TestBed` automatically for users. This assumes we already evaluated `zone.js/testing`.
getTestBed().initTestEnvironment(BrowserTestingModule, platformBrowserTesting(), {
getTestBed().initTestEnvironment([BrowserTestingModule, TestModule], platformBrowserTesting(), {
errorOnUnknownElements: true,
errorOnUnknownProperties: true,
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { NgModule, provideBrowserGlobalErrorListeners<% if(zoneless) { %>, provideZonelessChangeDetection<% } %> } from '@angular/core';
import { NgModule, provideBrowserGlobalErrorListeners } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
<% if (routing) { %>
import { AppRoutingModule } from './app-routing-module';<% } %>
Expand All @@ -13,8 +13,7 @@ import { App } from './app';
AppRoutingModule<% } %>
],
providers: [
provideBrowserGlobalErrorListeners()<% if (zoneless) { %>,
provideZonelessChangeDetection()<% } %>
provideBrowserGlobalErrorListeners()
],
bootstrap: [App]
})
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
<% if(zoneless) { %>import { provideZonelessChangeDetection } from '@angular/core';
<% } %>import { TestBed } from '@angular/core/testing';<% if (routing) { %>
import { TestBed } from '@angular/core/testing';<% if (routing) { %>
import { RouterModule } from '@angular/router';<% } %>
import { App } from './app';

Expand All @@ -11,8 +10,7 @@ describe('App', () => {
],<% } %>
declarations: [
App
],<% if(zoneless) { %>
providers: [provideZonelessChangeDetection()]<% } %>
],
}).compileComponents();
});

Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { ApplicationConfig, provideBrowserGlobalErrorListeners, <% if(!zoneless) { %>provideZoneChangeDetection<% } else { %>provideZonelessChangeDetection<% } %> } from '@angular/core';<% if (routing) { %>
import { ApplicationConfig, provideBrowserGlobalErrorListeners<% if(!zoneless) { %>, provideZoneChangeDetection<% } %> } from '@angular/core';<% if (routing) { %>
import { provideRouter } from '@angular/router';

import { routes } from './app.routes';<% } %>

export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
<% if(zoneless) { %>provideZonelessChangeDetection()<% } else { %>provideZoneChangeDetection({ eventCoalescing: true })<% } %>,
provideBrowserGlobalErrorListeners(),<% if(!zoneless) { %>
provideZoneChangeDetection({ eventCoalescing: true }),<% } %>
<% if (routing) {%>provideRouter(routes)<% } %>
]
};
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
<% if(zoneless) { %>import { provideZonelessChangeDetection } from '@angular/core';
<% } %>import { TestBed } from '@angular/core/testing';
import { TestBed } from '@angular/core/testing';
import { App } from './app';

describe('App', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [App],<% if(zoneless) { %>
providers: [provideZonelessChangeDetection()]<% } %>
imports: [App],
}).compileComponents();
});

Expand Down
53 changes: 5 additions & 48 deletions packages/schematics/angular/application/index_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ describe('Application Schematic', () => {
expect(pkg.devDependencies['less']).toEqual(latestVersions['less']);
});

it('should include zone.js if "zoneless" option is not present', async () => {
it('should _not_ include zone.js if "zoneless" option is not present', async () => {
const tree = await schematicRunner.runSchematic(
'application',
{
Expand All @@ -307,7 +307,7 @@ describe('Application Schematic', () => {
);

const pkg = JSON.parse(tree.readContent('/package.json'));
expect(pkg.dependencies['zone.js']).toEqual(latestVersions['zone.js']);
expect(pkg.dependencies['zone.js']).toBeUndefined();
});

it('should not include zone.js if "zoneless" option is true', async () => {
Expand Down Expand Up @@ -800,7 +800,7 @@ describe('Application Schematic', () => {
);
});

it('should add provideZonelessChangeDetection() in app-module.ts when zoneless is true', async () => {
it('should not add provideZonelessChangeDetection() in app-module.ts when zoneless is true', async () => {
const tree = await schematicRunner.runSchematic(
'application',
{
Expand All @@ -812,53 +812,10 @@ describe('Application Schematic', () => {
);
const path = '/projects/foo/src/app/app-module.ts';
const fileContent = tree.readContent(path);
expect(fileContent).toContain('provideZonelessChangeDetection()');
});

it('should not add provideZonelessChangeDetection() in app-module.ts when zoneless is false', async () => {
const tree = await schematicRunner.runSchematic(
'application',
{
...defaultOptions,
zoneless: false,
standalone: false,
},
workspaceTree,
);
const path = '/projects/foo/src/app/app-module.ts';
const fileContent = tree.readContent(path);
expect(fileContent).not.toContain('provideZonelessChangeDetection()');
});

it('should add provideZonelessChangeDetection() when zoneless is true', async () => {
const tree = await schematicRunner.runSchematic(
'application',
{
...defaultOptions,
zoneless: true,
},
workspaceTree,
);
const path = '/projects/foo/src/app/app.config.ts';
const fileContent = tree.readContent(path);
expect(fileContent).toContain('provideZonelessChangeDetection()');
});

it('should not add provideZonelessChangeDetection() when zoneless is false', async () => {
const tree = await schematicRunner.runSchematic(
'application',
{
...defaultOptions,
zoneless: false,
},
workspaceTree,
);
const path = '/projects/foo/src/app/app.config.ts';
const fileContent = tree.readContent(path);
expect(fileContent).not.toContain('provideZonelessChangeDetection()');
});

it('should not add provideZoneChangeDetection when zoneless is true', async () => {
it('should not add any change detection provider when zoneless is true', async () => {
const tree = await schematicRunner.runSchematic(
'application',
{
Expand All @@ -869,7 +826,7 @@ describe('Application Schematic', () => {
);
const path = '/projects/foo/src/app/app.config.ts';
const fileContent = tree.readContent(path);
expect(fileContent).not.toContain('provideZoneChangeDetection');
expect(fileContent).not.toMatch(/provideZone(less)?ChangeDetection/gi);
});
});

Expand Down
2 changes: 1 addition & 1 deletion packages/schematics/angular/application/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@
"description": "Generate an application that does not use `zone.js`.",
"x-prompt": "Do you want to create a 'zoneless' application without zone.js?",
"type": "boolean",
"default": false
"default": true
},
"fileNameStyleGuide": {
"type": "string",
Expand Down
3 changes: 2 additions & 1 deletion packages/schematics/angular/ng-new/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,8 @@
},
"zoneless": {
"description": "Create an initial application that does not utilize `zone.js`.",
"type": "boolean"
"type": "boolean",
"default": true
},
"aiConfig": {
"type": "array",
Expand Down
2 changes: 1 addition & 1 deletion tests/legacy-cli/e2e/initialize/500-create-project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export default async function () {
// Ensure local test registry is used when outside a project
await setNPMConfigRegistry(true);

await ng('new', 'test-project', '--skip-install');
await ng('new', 'test-project', '--skip-install', '--no-zoneless');
await expectFileToExist(join(process.cwd(), 'test-project'));
process.chdir('./test-project');

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,15 @@ import { updateJsonFile } from '../../../utils/project';
const snapshots = require('../../../ng-snapshot/package.json');

export default async function () {
await ng('generate', 'app', 'test-project-two', '--routing', '--no-standalone', '--skip-install');
await ng(
'generate',
'app',
'test-project-two',
'--routing',
'--no-standalone',
'--skip-install',
'--no-zoneless',
);
await ng('generate', 'app-shell', '--project', 'test-project-two');

const isSnapshotBuild = getGlobalVariable('argv')['ng-snapshots'];
Expand Down
11 changes: 9 additions & 2 deletions tests/legacy-cli/e2e/tests/build/jit-ngmodule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,15 @@ import { ng } from '../../utils/process';
import { updateJsonFile, useCIChrome, useCIDefaults } from '../../utils/project';

export default async function () {
await ng('generate', 'app', 'test-project-two', '--no-standalone', '--skip-install');
await ng('generate', 'private-e2e', '--related-app-name=test-project-two');
await ng(
'generate',
'app',
'test-project-two',
'--no-standalone',
'--skip-install',
'--no-zoneless',
);
await ng('generate', 'private-e2e', '--related-app-name=test-project-two', '--no-zoneless');

// Setup testing to use CI Chrome.
await useCIChrome('test-project-two', './projects/test-project-two/e2e');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,14 @@ export default async function () {
// forcibly remove in case another test doesn't clean itself up
await rimraf('node_modules/@angular/ssr');

await ng('generate', 'app', 'test-project-two', '--no-standalone', '--skip-install');
await ng(
'generate',
'app',
'test-project-two',
'--no-standalone',
'--skip-install',
'--no-zoneless',
);
await ng('generate', 'private-e2e', '--related-app-name=test-project-two');

// Setup testing to use CI Chrome.
Expand Down
4 changes: 2 additions & 2 deletions tests/legacy-cli/e2e/tests/commands/builder-project-by-cwd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { expectFileToExist } from '../../utils/fs';
import { ng } from '../../utils/process';

export default async function () {
await ng('generate', 'app', 'second-app', '--skip-install');
await ng('generate', 'app', 'third-app', '--skip-install');
await ng('generate', 'app', 'second-app', '--skip-install', '--no-zoneless');
await ng('generate', 'app', 'third-app', '--skip-install', '--no-zoneless');
const startCwd = process.cwd();

try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ export default async function () {
delete workspaceJson.projects['test-project'];
});

await ng('generate', 'app', 'second-app', '--skip-install');
await ng('generate', 'app', 'third-app', '--skip-install');
await ng('generate', 'app', 'second-app', '--skip-install', '--no-zoneless');
await ng('generate', 'app', 'third-app', '--skip-install', '--no-zoneless');

const startCwd = process.cwd();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { ng } from '../../../utils/process';
import { useCIChrome } from '../../../utils/project';

export default function () {
return ng('generate', 'application', 'app2')
return ng('generate', 'application', 'app2', '--no-zoneless')
.then(() => expectFileToMatch('angular.json', /\"app2\":/))
.then(() => useCIChrome('app2', 'projects/app2'))
.then(() => ng('test', 'app2', '--watch=false'));
Expand Down
Loading
Loading