Skip to content

Commit

Permalink
fix(localize): add polyfill in polyfills array instead of polyfills.ts (
Browse files Browse the repository at this point in the history
#47569)

With the recent changes in the Angular CLI (angular/angular-cli#23938) the polyfills option accepts module path that are resolved using Node module resolution. Also, the polyfills.ts file is no longer generated by default.

This commit changes the way on how the polyfill is added to the projects.

PR Close #47569
  • Loading branch information
alan-agius4 authored and AndrewKushnir committed Oct 3, 2022
1 parent 9eb3891 commit 400a6b5
Show file tree
Hide file tree
Showing 3 changed files with 150 additions and 141 deletions.
151 changes: 66 additions & 85 deletions packages/localize/schematics/ng-add/index.ts
Expand Up @@ -8,102 +8,96 @@
* @fileoverview Schematics for ng-new project that builds with Bazel.
*/

import {virtualFs, workspaces} from '@angular-devkit/core';
import {chain, noop, Rule, SchematicContext, SchematicsException, Tree} from '@angular-devkit/schematics';
import {tags} from '@angular-devkit/core';
import {chain, noop, Rule, SchematicContext, SchematicsException, Tree,} from '@angular-devkit/schematics';
import {NodePackageInstallTask} from '@angular-devkit/schematics/tasks';
import {addPackageJsonDependency, NodeDependencyType, removePackageJsonDependency} from '@schematics/angular/utility/dependencies';
import {getWorkspace} from '@schematics/angular/utility/workspace';
import {addPackageJsonDependency, NodeDependencyType, removePackageJsonDependency,} from '@schematics/angular/utility/dependencies';
import {allTargetOptions, getWorkspace, updateWorkspace,} from '@schematics/angular/utility/workspace';
import {Builders} from '@schematics/angular/utility/workspace-models';

import {Schema} from './schema';

export const localizePolyfill = `import '@angular/localize/init';`;
export const localizePolyfill = `@angular/localize/init`;

function getRelevantTargetDefinitions(
project: workspaces.ProjectDefinition, builderName: Builders): workspaces.TargetDefinition[] {
const definitions: workspaces.TargetDefinition[] = [];
project.targets.forEach((target: workspaces.TargetDefinition): void => {
if (target.builder === builderName) {
definitions.push(target);
function prependToMainFiles(projectName: string): Rule {
return async (host: Tree) => {
const workspace = await getWorkspace(host);
const project = workspace.projects.get(projectName);
if (!project) {
throw new SchematicsException(`Invalid project name (${projectName})`);
}
});
return definitions;
}

function getOptionValuesForTargetDefinition(
definition: workspaces.TargetDefinition, optionName: string): string[] {
const optionValues: string[] = [];
if (definition.options && optionName in definition.options) {
let optionValue: unknown = definition.options[optionName];
if (typeof optionValue === 'string') {
optionValues.push(optionValue);
}
}
if (!definition.configurations) {
return optionValues;
}
Object.values(definition.configurations)
.forEach((configuration: Record<string, unknown>|undefined): void => {
if (configuration && optionName in configuration) {
const optionValue: unknown = configuration[optionName];
if (typeof optionValue === 'string') {
optionValues.push(optionValue);
}
}
});
return optionValues;
}

function getFileListForRelevantTargetDefinitions(
project: workspaces.ProjectDefinition, builderName: Builders, optionName: string): string[] {
const fileList: string[] = [];
const definitions = getRelevantTargetDefinitions(project, builderName);
definitions.forEach((definition: workspaces.TargetDefinition): void => {
const optionValues = getOptionValuesForTargetDefinition(definition, optionName);
optionValues.forEach((filePath: string): void => {
if (fileList.indexOf(filePath) === -1) {
fileList.push(filePath);
const fileList = new Set<string>();
for (const target of project.targets.values()) {
if (target.builder !== Builders.Server) {
continue;
}
});
});
return fileList;
}

function prependToTargetFiles(
project: workspaces.ProjectDefinition, builderName: Builders, optionName: string, str: string) {
return (host: Tree) => {
const fileList = getFileListForRelevantTargetDefinitions(project, builderName, optionName);

fileList.forEach((path: string): void => {
const data = host.read(path);
if (!data) {
// If the file doesn't exist, just ignore it.
return;
for (const [, options] of allTargetOptions(target)) {
const value = options['main'];
if (typeof value === 'string') {
fileList.add(value);
}
}
}

const content = virtualFs.fileBufferToString(data);
if (content.includes(localizePolyfill) ||
content.includes(localizePolyfill.replace(/'/g, '"'))) {
for (const path of fileList) {
const content = host.readText(path);
if (content.includes(localizePolyfill)) {
// If the file already contains the polyfill (or variations), ignore it too.
return;
continue;
}

// Add string at the start of the file.
const recorder = host.beginUpdate(path);
recorder.insertLeft(0, str);

const localizeStr =
tags.stripIndents`/***************************************************************************************************
* Load \`$localize\` onto the global scope - used if i18n tags appear in Angular templates.
*/
import '${localizePolyfill}';
`;
recorder.insertLeft(0, localizeStr);
host.commitUpdate(recorder);
});
}
};
}

function moveToDependencies(host: Tree, context: SchematicContext) {
function addToPolyfillsOption(projectName: string): Rule {
return updateWorkspace((workspace) => {
const project = workspace.projects.get(projectName);
if (!project) {
throw new SchematicsException(`Invalid project name (${projectName})`);
}

for (const target of project.targets.values()) {
if (target.builder !== Builders.Browser && target.builder !== Builders.Karma) {
continue;
}

target.options ??= {};
target.options['polyfills'] ??= [localizePolyfill];

for (const [, options] of allTargetOptions(target)) {
// Convert polyfills option to array.
const polyfillsValue = typeof options['polyfills'] === 'string' ? [options['polyfills']] :
options['polyfills'];
if (Array.isArray(polyfillsValue) && !polyfillsValue.includes(localizePolyfill)) {
options['polyfills'] = [...polyfillsValue, localizePolyfill];
}
}
}
});
}

function moveToDependencies(host: Tree, context: SchematicContext): void {
if (host.exists('package.json')) {
// Remove the previous dependency and add in a new one under the desired type.
removePackageJsonDependency(host, '@angular/localize');
addPackageJsonDependency(host, {
name: '@angular/localize',
type: NodeDependencyType.Default,
version: `~0.0.0-PLACEHOLDER`
version: `~0.0.0-PLACEHOLDER`,
});

// Add a task to run the package manager. This is necessary because we updated
Expand All @@ -113,7 +107,7 @@ function moveToDependencies(host: Tree, context: SchematicContext) {
}

export default function(options: Schema): Rule {
return async (host: Tree) => {
return () => {
// We favor the name option because the project option has a
// smart default which can be populated even when unspecified by the user.
const projectName = options.name ?? options.project;
Expand All @@ -122,22 +116,9 @@ export default function(options: Schema): Rule {
throw new SchematicsException('Option "project" is required.');
}

const workspace = await getWorkspace(host);
const project: workspaces.ProjectDefinition|undefined = workspace.projects.get(projectName);
if (!project) {
throw new SchematicsException(`Invalid project name (${projectName})`);
}

const localizeStr =
`/***************************************************************************************************
* Load \`$localize\` onto the global scope - used if i18n tags appear in Angular templates.
*/
${localizePolyfill}
`;

return chain([
prependToTargetFiles(project, Builders.Browser, 'polyfills', localizeStr),
prependToTargetFiles(project, Builders.Server, 'main', localizeStr),
prependToMainFiles(projectName),
addToPolyfillsOption(projectName),
// If `$localize` will be used at runtime then must install `@angular/localize`
// into `dependencies`, rather than the default of `devDependencies`.
options.useAtRuntime ? moveToDependencies : noop(),
Expand Down

0 comments on commit 400a6b5

Please sign in to comment.