在 v13 的 angular.json 中替换“deployUrl”的最佳方法是什么?

问题描述 投票:0回答:4

我目前正在将我的应用程序从 v12 升级到 v13,并注意到弹出此警告:

Option "deployUrl" is deprecated: Use "baseHref" option, "APP_BASE_HREF" DI token or a combination of both instead. For more information, see https://angular.io/guide/deployment#the-deploy-url.

深入研究之后,“baseHref”或 APP_BASE_REF 选项都不适用于我的设置,所以我想知道我是否错误地使用了它们,或者是否没有好的方法来替换它

这是来自 angular.json 的应用程序配置片段:

    "dashboard": {
      "projectType": "application",
      "root": "apps/dashboard",
      "sourceRoot": "apps/dashboard/src",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "allowedCommonJsDependencies": [],
            "outputPath": "../dist/dashboard/",
            "deployUrl": "/dist/dashboard/",
            "index": "apps/dashboard/src/index.html",
            "main": "apps/dashboard/src/main.ts",
            "tsConfig": "apps/dashboard/tsconfig.app.json",
            "polyfills": "apps/dashboard/src/polyfills.ts",
            "styles": [
              "apps/dashboard/src/styles.scss"
            ],
            "scripts": [],
            "stylePreprocessorOptions": {
              "includePaths": [
                "libs/assets/styles"
              ]
            },
            "aot": false,
            "vendorChunk": true,
            "extractLicenses": false,
            "buildOptimizer": false,
            "sourceMap": true,
            "optimization": false,
            "namedChunks": true
          },
          "configurations": {
            "production": {
              "aot": true,
              "buildOptimizer": true,
              "extractLicenses": true,
              "fileReplacements": [
                {
                  "replace": "apps/dashboard/src/environments/environment.ts",
                  "with": "apps/dashboard/src/environments/environment.prod.ts"
                }
              ],
              "namedChunks": false,
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "vendorChunk": false
            },
            "es5": {
              "tsConfig": "apps/dashboard/tsconfig.es5.json"
            }
          },
          "defaultConfiguration": ""
        }
      }
    }

路由文件片段:

export const DashboardRoutes: Routes = [
    { path: '', pathMatch: 'full', redirectTo: '/dashboard' },
    {
        path: 'dashboard',
        data: {
            label: 'Dashboard',
            appBase: true
        },
        children: [
            // this is a child so we can load the component in same router-outlet
            {
                path: '',
                loadChildren: () => import('./dashboard/dashboard.module').then(m => m.DashboardModule),
                data: {
                    authorizedRoles: ['member'],
                }
            },
            // ...other children
        ]
    }
]

我尝试将deployUrl更改为baseHref,这有点效果-它将主页从

localhost/dashboard
更改为
localhost/dist/dashboard/dashboard
(显然不正确),并且仅放置一个空字符串或“/”不会加载应用程序正确(像应该那样查看 dist/ 与 dist/dashboard)

值得注意的是,我的index.html确实使用了

<base href="/" />
并且APP_BASE_HREF在应用程序模块提供程序中没有被覆盖

json angular configuration angular13
4个回答
7
投票

最终找到了一些东西来代替它:

  • 在 angular.json 中将“deployUrl”替换为“baseHref”
  • 在 app.module 中添加了 APP_BASE_HREF 覆盖
    • { provide: APP_BASE_HREF, useValue: '/' }
  • 替换了index.html中引用dist(输出)文件夹的所有href
    • 例如将 'dist/assets/{some_asset}' 替换为 '../assets/{some_asset'}'
  • index.html 仍然使用
    <base href="/">

6
投票

这是 Angular 13+ 的问题

在这里找到了解决方案: https://github.com/angular/angular-cli/issues/22113#issuecomment-1004279867

您应该将以下代码放入 main.ts 文件中:

declare var  __webpack_public_path__: string;
__webpack_public_path__ = 'valueFormerlyAssignedUsing_deployUrl';

valueFormerlyAssignedUsing_deployUrl
替换为包含块的文件夹路径。


0
投票

我当前的 Angular 版本是 14,因为 Angular 13 简化了部署Url。

如果您使用 CDN 缓存,但您的应用程序运行在不同的域(例如云服务器或云功能)上,则会造成麻烦。

这是一步一步的解决方案:

  1. 删除deployUrl,不用改成baseHref,我们保持默认

  2. 替换url以通过replace-file.js手动加载:

const replace = require('replace-in-file');

const prefix = 'https://your-cdn.com/assets';

const action2options = {
  files: path.join(process.cwd(), '/dist/browser/index.html'),
  from: [/<script src="(.*?)"/g],
  to: [`<script src="${prefix}$1"`],
};


replace(action2options)
  .then(results => {
    // console.log('Replacement results:', results);
  })
  .catch(error => {
    console.error('Error occurred:', error);
  });
  1. 通过将此行添加到 main.ts 来使用资产 CDN 加载块(如果使用通用,也将其添加到 main.server.ts 中:
// main.ts add it
// main.server.ts add it too if use universal
// https://github.com/angular/angular-cli/issues/22113#issuecomment-1004279867
declare var __webpack_public_path__: string;
__webpack_public_path__ = 'https://your-cdn.com/assets';

如果您需要按环境更改链接,请使用此检测:

// angular.json => add to build -> scripts file

            {
                "input": "src/environments/replacer-build.js",
                "inject": false,
                "bundleName": "replacer-build.development"
              }
// update to production build too:
  "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],

之后你可以通过以下方式在replace-file.js中检测到它:

const fs = require('fs');

const files = fs.readdirSync(path.join(process.cwd(), '/dist/browser')).filter(file => {
  return file.match(/^replacer-build\.(development|production|staging)\.js$/);
});

let env = '';
let assetUrl = '';
if (files.length > 0) {
  const filename = files[0];
  if (filename.includes('development')) {
    env = 'development';
    assetUrl = 'http://localhost:4200/';
  else if (filename.includes('production')) {
    env = 'production';
    assetUrl = 'https://your-cdn.com/assets';
  }
}


console.log(`The current environment is ${env} and assetURL replace to:`, assetUrl);

之后您可以在服务器上加载系统,但通过 CDN 加载资产


0
投票

Angular v17之后,已经使用vite和esbuild来替代webpack。是不是不能使用webpack_public_path

© www.soinside.com 2019 - 2024. All rights reserved.