From b4cd4576e4b1cd085e002a4aa95f7fd5b0175cc1 Mon Sep 17 00:00:00 2001 From: sumeyye Date: Mon, 9 Nov 2026 14:02:06 +0300 Subject: [PATCH 1/2] Fixed Angular PWA support by dynamically determining the @angular/pwa version based on the @angular/cli version in package.json. --- .../framework/ui/angular/pwa-configuration.md | 93 ++++++++++--------- .../AngularPwaSupportAdder.cs | 34 ++++++- 2 files changed, 84 insertions(+), 43 deletions(-) diff --git a/docs/en/framework/ui/angular/pwa-configuration.md b/docs/en/framework/ui/angular/pwa-configuration.md index 4c10fb6d27..23935bbdcf 100644 --- a/docs/en/framework/ui/angular/pwa-configuration.md +++ b/docs/en/framework/ui/angular/pwa-configuration.md @@ -11,24 +11,26 @@ Converting your Angular application to a PWA is easy. +> If you created your solution with the **Progressive Web Application** option (in ABP Studio, or with the `-pwa` parameter of the `abp new` command), step 1 has already been done for you. Check the `assets` configuration described at the end of step 1, then continue from [step 2](#2-update-the-web-app-manifest). + ## 1. Install Angular PWA -Run the following command in the root folder of your Angular application: +Run the following command in the root folder of your Angular application. Use the `@angular/pwa` version whose major version matches the `@angular/cli` version in your `package.json` (for example, `@angular/pwa@22` for Angular 22): ```shell -yarn ng add @angular/pwa +yarn ng add @angular/pwa@ ``` ...or... ```shell -npm run ng add @angular/pwa +npx ng add @angular/pwa@ ``` This will install the `@angular/service-worker` package and make your default app a PWA. Alternatively, you may add `project` parameter to target a specific app in your workspace: ```shell -yarn ng add @angular/pwa --project MyProjectName +yarn ng add @angular/pwa@ --project MyProjectName ``` Here is the output of the command: @@ -38,17 +40,24 @@ Here is the output of the command: So, Angular CLI updates some files and add a few others: - **ngsw-config.json** is where the [service worker configuration](https://angular.dev/ecosystem/service-workers/config) is placed. Not all PWAs have this file. It is specific to Angular. -- **manifest.webmanifest** is a [web app manifest](https://developer.mozilla.org/en-US/docs/Web/Manifest) and provides information about your app in JSON format. -- **icons** are placeholder icons that are referred to in your web app manifest. We will replace these in a minute. -- **angular.json** has following modifications: - - `assets` include _manifest.webmanifest_. - - `serviceWorker` is `true` in production build. - - `ngswConfigPath` refers to _ngsw-config.json_. +- **public/manifest.webmanifest** is a [web app manifest](https://developer.mozilla.org/en-US/docs/Web/Manifest) and provides information about your app in JSON format. +- **public/icons** are placeholder icons that are referred to in your web app manifest. We will replace these in a minute. +- **angular.json** has the `serviceWorker` option set to _ngsw-config.json_ in the production configuration. - **package.json** has _@angular/service-worker_ as a new dependency. -- **app.config.ts** The `provideServiceWorker` provider is imported to register the service worker script. -- **index.html** has following modifications: - - A `` element that refers to _manifest.webmanifest_. - - A `` tag that sets a theme color. +- **main.ts** (or **app.config.ts**) registers the service worker script with the `provideServiceWorker` provider. In the ABP startup templates, `main.ts` passes the application configuration to `bootstrapApplication` directly, so the provider is added to `main.ts`. +- **index.html** has a `` element that refers to _manifest.webmanifest_. + +The manifest and the icons are placed in the `public` folder. Make sure this folder is copied to the build output. If the `assets` array of your application in `angular.json` does not include it, add it: + +```json +"assets": [ + "src/favicon.ico", + "src/assets", + { "glob": "**/*", "input": "public" } +] +``` + +Otherwise, the browser cannot find the manifest and the icons, and the application cannot be installed. ## 2. Update the Web App Manifest @@ -97,7 +106,7 @@ Open the _manifest.webmanifest_ file and update `theme_color` and `background_co } ``` -Then open _index.html_ and change the theme color meta tag as below: +Then open _index.html_ and add (or update) the theme color meta tag as below: ```html @@ -119,7 +128,7 @@ First, open the _manifest.webmanifest_ file and remove all elements in the `icon Then, run the following command in your terminal (changing the path of course): ```shell -npx pwa-asset-generator /path/to/your/logo.png ./src/assets/pwa -i ./src/index.html -m ./src/manifest.webmanifest +npx pwa-asset-generator /path/to/your/logo.png ./public/pwa -i ./src/index.html -m ./public/manifest.webmanifest ``` Open the _manifest.webmanifest_ file again. You will see this: @@ -150,134 +159,134 @@ In addition to updated icons, the library will generate splash screens. However, ``` diff --git a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectModification/AngularPwaSupportAdder.cs b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectModification/AngularPwaSupportAdder.cs index 86880aaacf..8c0ae98385 100644 --- a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectModification/AngularPwaSupportAdder.cs +++ b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectModification/AngularPwaSupportAdder.cs @@ -1,6 +1,8 @@ using System; using System.IO; using System.Linq; +using System.Text.RegularExpressions; +using Newtonsoft.Json.Linq; using Volo.Abp.Cli.Utils; using Volo.Abp.DependencyInjection; @@ -29,7 +31,37 @@ public class AngularPwaSupportAdder : ITransientDependency protected virtual void AddPwaSupportToProject(string filePath) { var directory = Path.GetDirectoryName(filePath).EnsureEndsWith(Path.DirectorySeparatorChar); + var pwaMajorVersion = GetAngularCliMajorVersion(filePath); - CmdHelper.RunCmd("ng add @angular/pwa@13 --skip-confirmation", workingDirectory: directory); + CmdHelper.RunCmd( + $"ng add @angular/pwa@{pwaMajorVersion} --skip-confirmation", + out var exitCode, + workingDirectory: directory + ); + + if (exitCode != 0) + { + throw new AbpException( + $"Failed to add Angular PWA support to '{filePath}'. 'ng add @angular/pwa@{pwaMajorVersion}' exited with code {exitCode}." + ); + } + } + + protected virtual string GetAngularCliMajorVersion(string packageJsonFilePath) + { + var packageJson = JObject.Parse(File.ReadAllText(packageJsonFilePath)); + + var cliVersion = + (packageJson["devDependencies"]?["@angular/cli"] ?? packageJson["dependencies"]?["@angular/cli"])?.ToString(); + + var match = cliVersion == null ? null : Regex.Match(cliVersion, @"\d+"); + if (match == null || !match.Success) + { + throw new AbpException( + $"Could not determine the @angular/cli version from '{packageJsonFilePath}', so the matching @angular/pwa version cannot be selected." + ); + } + + return match.Value; } } From 611ad64b7b88c17f05dd2e72f45298aa3bb2f98b Mon Sep 17 00:00:00 2001 From: maliming Date: Tue, 10 Nov 2026 11:27:38 +0800 Subject: [PATCH 2/2] Run ng add through npx and add the public folder to build assets --- .../framework/ui/angular/pwa-configuration.md | 4 +- .../AngularPwaSupportAdder.cs | 54 ++++- .../AngularPwaSupportAdder_Tests.cs | 229 ++++++++++++++++++ 3 files changed, 284 insertions(+), 3 deletions(-) create mode 100644 framework/test/Volo.Abp.Cli.Core.Tests/Volo/Abp/Cli/ProjectModification/AngularPwaSupportAdder_Tests.cs diff --git a/docs/en/framework/ui/angular/pwa-configuration.md b/docs/en/framework/ui/angular/pwa-configuration.md index 23935bbdcf..93afc0f80d 100644 --- a/docs/en/framework/ui/angular/pwa-configuration.md +++ b/docs/en/framework/ui/angular/pwa-configuration.md @@ -11,7 +11,7 @@ Converting your Angular application to a PWA is easy. -> If you created your solution with the **Progressive Web Application** option (in ABP Studio, or with the `-pwa` parameter of the `abp new` command), step 1 has already been done for you. Check the `assets` configuration described at the end of step 1, then continue from [step 2](#2-update-the-web-app-manifest). +> If you created your solution with the **Progressive Web Application** option (in ABP Studio, or with the `-pwa` parameter of the `abp new` command), step 1 has already been done for you, including the `assets` configuration described at the end of step 1. You can continue from [step 2](#2-update-the-web-app-manifest). ## 1. Install Angular PWA @@ -47,7 +47,7 @@ So, Angular CLI updates some files and add a few others: - **main.ts** (or **app.config.ts**) registers the service worker script with the `provideServiceWorker` provider. In the ABP startup templates, `main.ts` passes the application configuration to `bootstrapApplication` directly, so the provider is added to `main.ts`. - **index.html** has a `` element that refers to _manifest.webmanifest_. -The manifest and the icons are placed in the `public` folder. Make sure this folder is copied to the build output. If the `assets` array of your application in `angular.json` does not include it, add it: +The manifest and the icons are placed in the `public` folder. Make sure this folder is copied to the build output. If the build `assets` array of your application in `angular.json` does not include it, add it (this is done automatically for solutions created with the **Progressive Web Application** option): ```json "assets": [ diff --git a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectModification/AngularPwaSupportAdder.cs b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectModification/AngularPwaSupportAdder.cs index 8c0ae98385..84c26087b7 100644 --- a/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectModification/AngularPwaSupportAdder.cs +++ b/framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/ProjectModification/AngularPwaSupportAdder.cs @@ -2,6 +2,7 @@ using System.IO; using System.Linq; using System.Text.RegularExpressions; +using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Volo.Abp.Cli.Utils; using Volo.Abp.DependencyInjection; @@ -33,8 +34,9 @@ public class AngularPwaSupportAdder : ITransientDependency var directory = Path.GetDirectoryName(filePath).EnsureEndsWith(Path.DirectorySeparatorChar); var pwaMajorVersion = GetAngularCliMajorVersion(filePath); + // "ng" is usually not on the PATH and node_modules may not be installed yet, so the Angular CLI is run through npx. CmdHelper.RunCmd( - $"ng add @angular/pwa@{pwaMajorVersion} --skip-confirmation", + $"npx -y -p @angular/cli@{pwaMajorVersion} ng add @angular/pwa@{pwaMajorVersion} --skip-confirmation", out var exitCode, workingDirectory: directory ); @@ -45,6 +47,15 @@ public class AngularPwaSupportAdder : ITransientDependency $"Failed to add Angular PWA support to '{filePath}'. 'ng add @angular/pwa@{pwaMajorVersion}' exited with code {exitCode}." ); } + + var angularJsonFilePath = Path.Combine(directory, "angular.json"); + var angularJson = File.ReadAllText(angularJsonFilePath); + var updatedAngularJson = AddPublicFolderToBuildAssets(angularJson, directory); + + if (updatedAngularJson != angularJson) + { + File.WriteAllText(angularJsonFilePath, updatedAngularJson); + } } protected virtual string GetAngularCliMajorVersion(string packageJsonFilePath) @@ -64,4 +75,45 @@ public class AngularPwaSupportAdder : ITransientDependency return match.Value; } + + // "ng add @angular/pwa" puts the manifest and the icons into the "public" folder of the project, + // which is not copied to the build output unless the build assets include it. + protected virtual string AddPublicFolderToBuildAssets(string angularJson, string workspaceDirectory) + { + var json = JObject.Parse(angularJson); + var changed = false; + + foreach (var project in json["projects"]?.Children() ?? Enumerable.Empty()) + { + if (project.Value.SelectToken("architect.build.options.assets") is not JArray assets) + { + continue; + } + + var projectRoot = project.Value["root"]?.ToString().Replace('\\', '/').TrimEnd('/'); + var publicFolder = projectRoot.IsNullOrEmpty() ? "public" : projectRoot + "/public"; + + if (!Directory.Exists(Path.Combine(workspaceDirectory, publicFolder)) || + assets.OfType().Any(x => x["input"]?.ToString().Replace('\\', '/').TrimEnd('/') == publicFolder)) + { + continue; + } + + assets.Add(new JObject + { + ["glob"] = "**/*", + ["input"] = publicFolder + }); + changed = true; + } + + if (!changed) + { + return angularJson; + } + + var newLine = angularJson.Contains("\r\n") ? "\r\n" : "\n"; + var result = json.ToString(Formatting.Indented).Replace("\r\n", "\n").Replace("\n", newLine); + return angularJson.EndsWith("\n") ? result + newLine : result; + } } diff --git a/framework/test/Volo.Abp.Cli.Core.Tests/Volo/Abp/Cli/ProjectModification/AngularPwaSupportAdder_Tests.cs b/framework/test/Volo.Abp.Cli.Core.Tests/Volo/Abp/Cli/ProjectModification/AngularPwaSupportAdder_Tests.cs new file mode 100644 index 0000000000..d59cee78de --- /dev/null +++ b/framework/test/Volo.Abp.Cli.Core.Tests/Volo/Abp/Cli/ProjectModification/AngularPwaSupportAdder_Tests.cs @@ -0,0 +1,229 @@ +using System; +using System.IO; +using System.Linq; +using Newtonsoft.Json.Linq; +using NSubstitute; +using Shouldly; +using Volo.Abp.Cli.Utils; +using Xunit; + +namespace Volo.Abp.Cli.ProjectModification; + +public class AngularPwaSupportAdder_Tests : IDisposable +{ + private static readonly string AngularJson = """ + { + "version": 1, + "projects": { + "MyProjectName": { + "projectType": "application", + "root": "", + "architect": { + "build": { + "options": { + "polyfills": ["src/polyfills.ts"], + "assets": [ + "src/favicon.ico", + "src/assets", + { + "glob": "web.config", + "input": ".", + "output": "." + } + ] + } + }, + "test": { + "options": { + "assets": ["src/assets"] + } + } + } + } + } + } + """.Replace("\r\n", "\n"); + + private readonly string _testDirectory; + private readonly TestAngularPwaSupportAdder _adder; + + public AngularPwaSupportAdder_Tests() + { + _testDirectory = Path.Combine(Path.GetTempPath(), "abp-cli-tests", Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(_testDirectory); + + _adder = new TestAngularPwaSupportAdder(Substitute.For(), new PackageJsonFileFinder()); + } + + public void Dispose() + { + Directory.Delete(_testDirectory, recursive: true); + } + + [Theory] + [InlineData("{ \"devDependencies\": { \"@angular/cli\": \"~22.0.0\" } }", "22")] + [InlineData("{ \"devDependencies\": { \"@angular/cli\": \"^21.1.3\" } }", "21")] + [InlineData("{ \"devDependencies\": { \"@angular/cli\": \"22\" } }", "22")] + [InlineData("{ \"dependencies\": { \"@angular/cli\": \"~20.3.0\" } }", "20")] + [InlineData("{ \"dependencies\": { \"@angular/cli\": \"~20.3.0\" }, \"devDependencies\": { \"@angular/cli\": \"~22.0.0\" } }", "22")] + public void Should_Get_Angular_Cli_Major_Version(string packageJson, string expectedVersion) + { + _adder.GetAngularCliMajorVersion(WritePackageJson(packageJson)).ShouldBe(expectedVersion); + } + + [Theory] + [InlineData("{ \"devDependencies\": { \"typescript\": \"~5.9.0\" } }")] + [InlineData("{ \"devDependencies\": { \"@angular/cli\": \"latest\" } }")] + public void Should_Throw_If_Angular_Cli_Version_Cannot_Be_Determined(string packageJson) + { + Should.Throw(() => _adder.GetAngularCliMajorVersion(WritePackageJson(packageJson))); + } + + [Fact] + public void Should_Add_Public_Folder_To_Build_Assets() + { + Directory.CreateDirectory(Path.Combine(_testDirectory, "public")); + + var result = _adder.AddPublicFolderToBuildAssets(AngularJson, _testDirectory); + + var assets = GetAssets(result, "build"); + assets.Count.ShouldBe(4); + assets[0].ToString().ShouldBe("src/favicon.ico"); + assets[1].ToString().ShouldBe("src/assets"); + assets[2]["glob"].ToString().ShouldBe("web.config"); + assets[3]["glob"].ToString().ShouldBe("**/*"); + assets[3]["input"].ToString().ShouldBe("public"); + + GetAssets(result, "test").Count.ShouldBe(1); + result.ShouldEndWith("}"); + _adder.AddPublicFolderToBuildAssets(AngularJson + "\n", _testDirectory).ShouldEndWith("}\n"); + } + + [Fact] + public void Should_Not_Add_Public_Folder_To_Build_Assets_Twice() + { + Directory.CreateDirectory(Path.Combine(_testDirectory, "public")); + + var result = _adder.AddPublicFolderToBuildAssets(AngularJson, _testDirectory); + + _adder.AddPublicFolderToBuildAssets(result, _testDirectory).ShouldBe(result); + GetAssets(result, "build").Count(x => x is JObject && x["input"]?.ToString() == "public").ShouldBe(1); + } + + [Fact] + public void Should_Not_Add_Public_Folder_To_Build_Assets_If_It_Does_Not_Exist() + { + _adder.AddPublicFolderToBuildAssets(AngularJson, _testDirectory).ShouldBe(AngularJson); + } + + [Fact] + public void Should_Add_Public_Folder_Of_Project_Root_To_Build_Assets() + { + Directory.CreateDirectory(Path.Combine(_testDirectory, "projects", "app", "public")); + var angularJson = AngularJson.Replace("\"root\": \"\"", "\"root\": \"projects/app\""); + + var result = _adder.AddPublicFolderToBuildAssets(angularJson, _testDirectory); + + GetAssets(result, "build").Last()["input"].ToString().ShouldBe("projects/app/public"); + } + + [Fact] + public void Should_Keep_Line_Endings() + { + Directory.CreateDirectory(Path.Combine(_testDirectory, "public")); + + var result = _adder.AddPublicFolderToBuildAssets(AngularJson.Replace("\n", "\r\n"), _testDirectory); + + GetAssets(result, "build").Last()["input"].ToString().ShouldBe("public"); + result.ShouldContain("\r\n"); + result.Replace("\r\n", string.Empty).ShouldNotContain("\n"); + } + + [Theory] + [InlineData("[\"src/favicon.ico\"]", 2)] + [InlineData("[]", 1)] + public void Should_Add_Public_Folder_To_Inline_Build_Assets(string assets, int expectedCount) + { + Directory.CreateDirectory(Path.Combine(_testDirectory, "public")); + var angularJson = $"{{ \"projects\": {{ \"app\": {{ \"root\": \"\", \"architect\": {{ \"build\": {{ \"options\": {{ \"assets\": {assets} }} }} }} }} }} }}"; + + var result = (JArray)JObject.Parse(_adder.AddPublicFolderToBuildAssets(angularJson, _testDirectory)) + ["projects"]!["app"]!["architect"]!["build"]!["options"]!["assets"]; + + result.Count.ShouldBe(expectedCount); + result.Last()["input"]!.ToString().ShouldBe("public"); + } + + [Fact] + public void Should_Run_Ng_Add_Through_Npx_And_Add_Public_Folder_To_Build_Assets() + { + var cmdHelper = CreateCmdHelper(exitCode: 0); + WritePackageJson("{ \"devDependencies\": { \"@angular/cli\": \"~22.0.0\" } }"); + var angularJsonPath = Path.Combine(_testDirectory, "angular.json"); + File.WriteAllText(angularJsonPath, AngularJson); + + new AngularPwaSupportAdder(cmdHelper, new PackageJsonFileFinder()).AddPwaSupport(_testDirectory); + + cmdHelper.Received(1).RunCmd( + "npx -y -p @angular/cli@22 ng add @angular/pwa@22 --skip-confirmation", + out Arg.Any(), + _testDirectory + Path.DirectorySeparatorChar); + GetAssets(File.ReadAllText(angularJsonPath), "build").Last()["input"].ToString().ShouldBe("public"); + } + + [Fact] + public void Should_Throw_If_Ng_Add_Fails() + { + var cmdHelper = CreateCmdHelper(exitCode: 127); + WritePackageJson("{ \"devDependencies\": { \"@angular/cli\": \"~22.0.0\" } }"); + var angularJsonPath = Path.Combine(_testDirectory, "angular.json"); + File.WriteAllText(angularJsonPath, AngularJson); + + Should.Throw(() => new AngularPwaSupportAdder(cmdHelper, new PackageJsonFileFinder()).AddPwaSupport(_testDirectory)); + + File.ReadAllText(angularJsonPath).ShouldBe(AngularJson); + } + + private ICmdHelper CreateCmdHelper(int exitCode) + { + var cmdHelper = Substitute.For(); + cmdHelper + .When(x => x.RunCmd(Arg.Any(), out Arg.Any(), Arg.Any())) + .Do(call => + { + call[1] = exitCode; + Directory.CreateDirectory(Path.Combine(_testDirectory, "public")); + }); + return cmdHelper; + } + + private string WritePackageJson(string content) + { + var path = Path.Combine(_testDirectory, "package.json"); + File.WriteAllText(path, content); + return path; + } + + private static JArray GetAssets(string angularJson, string target) + { + return (JArray)JObject.Parse(angularJson)["projects"]!["MyProjectName"]!["architect"]![target]!["options"]!["assets"]; + } + + private class TestAngularPwaSupportAdder : AngularPwaSupportAdder + { + public TestAngularPwaSupportAdder(ICmdHelper cmdHelper, PackageJsonFileFinder packageJsonFileFinder) + : base(cmdHelper, packageJsonFileFinder) + { + } + + public new string GetAngularCliMajorVersion(string packageJsonFilePath) + { + return base.GetAngularCliMajorVersion(packageJsonFilePath); + } + + public new string AddPublicFolderToBuildAssets(string angularJson, string workspaceDirectory) + { + return base.AddPublicFolderToBuildAssets(angularJson, workspaceDirectory); + } + } +}