Skip to content

Auto include @angular/platform-server/init and @angular/localize/init #24032

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

Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export const KARMA_BUILDER_INFO = Object.freeze({
* Also disables progress reporting to minimize logging output.
*/
export const BASE_OPTIONS = Object.freeze<Schema>({
polyfills: ['zone.js', 'zone.js/testing', '@angular/localize/init'],
polyfills: ['zone.js', 'zone.js/testing'],
tsConfig: 'src/tsconfig.spec.json',
karmaConfig: 'karma.conf.js',
browsers: 'ChromeHeadlessCI',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,14 +96,33 @@ export async function getCommonConfig(wco: WebpackConfigOptions): Promise<Config
extraPlugins.push(new ProgressPlugin(platform));
}

const localizePackageInitEntryPoint = '@angular/localize/init';
const hasLocalizeType = tsConfig.options.types?.some(
(t) => t === '@angular/localize' || t === localizePackageInitEntryPoint,
);

if (hasLocalizeType) {
entryPoints['main'] = [localizePackageInitEntryPoint];
}

if (buildOptions.main) {
const mainPath = path.resolve(root, buildOptions.main);
entryPoints['main'] = [mainPath];
if (Array.isArray(entryPoints['main'])) {
entryPoints['main'].push(mainPath);
} else {
entryPoints['main'] = [mainPath];
}
}

if (isPlatformServer) {
// Fixes Critical dependency: the request of a dependency is an expression
extraPlugins.push(new ContextReplacementPlugin(/@?hapi|express[\\/]/));

if (Array.isArray(entryPoints['main'])) {
// This import must come before any imports (direct or transitive) that rely on DOM built-ins being
// available, such as `@angular/elements`.
entryPoints['main'].unshift('@angular/platform-server/init');
}
}

if (polyfills?.length) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"polyfills": ["zone.js", "zone.js/testing", "@angular/localize/init"],
"polyfills": ["zone.js", "zone.js/testing"],

"tsConfig": "src/tsconfig.spec.json",
"karmaConfig": "karma.conf.js",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,4 @@
* found in the LICENSE file at https://angular.io/license
*/

import '@angular/localize/init';

export { AppServerModule } from './app/app.server.module';
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,6 @@
*/
// import 'web-animations-js'; // Run `npm install --save web-animations-js`.


import '@angular/localize/init';

/**
* By default, zone.js will patch all possible macroTask and DomEvents
* user can disable parts of macroTask/DomEvents patch by setting following flags
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"types": []
"types": ["@angular/localize/init"]
},
"files": [
"main.ts",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"outDir": "../dist-server",
"target": "es2016",
"baseUrl": "./",
"types": []
"types": ["@angular/localize/init"]
},
"files": [
"main.server.ts"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
"compilerOptions": {
"outDir": "../out-tsc/spec",
"types": [
"jasmine"
"jasmine",
"@angular/localize/init"
]
},
"files": [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
"outDir": "<%= relativePathToWorkspaceRoot %>/out-tsc/server",
"target": "es2019",
"types": [
"node"
"node"<% if (hasLocalizePackage) { %>,
"@angular/localize/init"<% } %>
]
},
"files": [
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,2 @@
/***************************************************************************************************
* Initialize the server environment - for example, adding DOM built-in types to the global scope.
*
* NOTE:
* This import must come before any imports (direct or transitive) that rely on DOM built-ins being
* available, such as `@angular/elements`.
*/
import '@angular/platform-server/init';

<% if (hasLocalizePackage) { %>/***************************************************************************************************
* Load `$localize` onto the global scope - used if i18n tags appear in Angular templates.
*/
import '@angular/localize/init';

<% } %>
export { <%= rootModuleClassName %> } from './app/<%= stripTsExtension(rootModuleFileName) %>';
2 changes: 1 addition & 1 deletion packages/schematics/angular/universal/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,6 @@ export default function (options: UniversalOptions): Rule {
...strings,
...options,
stripTsExtension: (s: string) => s.replace(/\.ts$/, ''),
hasLocalizePackage: !!getPackageJsonDependency(host, '@angular/localize'),
}),
move(join(normalize(clientProject.root), 'src')),
]);
Expand All @@ -273,6 +272,7 @@ export default function (options: UniversalOptions): Rule {
...options,
stripTsExtension: (s: string) => s.replace(/\.ts$/, ''),
tsConfigExtends,
hasLocalizePackage: !!getPackageJsonDependency(host, '@angular/localize'),
relativePathToWorkspaceRoot: relativePathToWorkspaceRoot(tsConfigDirectory),
}),
move(tsConfigDirectory),
Expand Down
30 changes: 12 additions & 18 deletions packages/schematics/angular/universal/index_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing';
import { parse as parseJson } from 'jsonc-parser';
import { Schema as ApplicationOptions, Style } from '../application/schema';
import { CompilerOptions } from '../third_party/github.com/Microsoft/TypeScript/lib/typescript';
import { NodeDependencyType, addPackageJsonDependency } from '../utility/dependencies';
import { Schema as WorkspaceOptions } from '../workspace/schema';
import { Schema as UniversalOptions } from './schema';
Expand Down Expand Up @@ -225,36 +226,29 @@ describe('Universal Schematic', () => {
expect(tree.exists(filePath)).toEqual(true);
});

it(`should add import to '@angular/platform-server/init' in main file`, async () => {
it(`should not add import to '@angular/localize' as type in 'tsconfig.server.json' when it's not a depedency`, async () => {
const tree = await schematicRunner
.runSchematicAsync('universal', defaultOptions, appTree)
.toPromise();
const filePath = '/projects/bar/src/main.server.ts';
const contents = tree.readContent(filePath);
expect(contents).toContain("import '@angular/platform-server/init'");
const { compilerOptions } = tree.readJson('/projects/bar/tsconfig.server.json') as {
compilerOptions: CompilerOptions;
};
expect(compilerOptions.types).not.toContain('@angular/localize/init');
});

it(`should not add import to '@angular/localize' in main file when it's not a depedency`, async () => {
const tree = await schematicRunner
.runSchematicAsync('universal', defaultOptions, appTree)
.toPromise();
const filePath = '/projects/bar/src/main.server.ts';
const contents = tree.readContent(filePath);
expect(contents).not.toContain('@angular/localize');
});

it(`should add import to '@angular/localize' in main file when it's a depedency`, async () => {
it(`should add import to '@angular/localize' as type in 'tsconfig.server.json' when it's not a depedency`, async () => {
addPackageJsonDependency(appTree, {
name: '@angular/localize',
type: NodeDependencyType.Default,
version: 'latest',
});

const tree = await schematicRunner
.runSchematicAsync('universal', defaultOptions, appTree)
.toPromise();
const filePath = '/projects/bar/src/main.server.ts';
const contents = tree.readContent(filePath);
expect(contents).toContain('@angular/localize/init');

const { compilerOptions } = tree.readJson('/projects/bar/tsconfig.server.json') as {
compilerOptions: CompilerOptions;
};
expect(compilerOptions.types).toContain('@angular/localize/init');
});
});