在访问本地静态文件之前在 angular 服务器中重写 URL

Rewrite URL in angular server before accessing local static file

我正在开发一个 angular (v.10) 应用程序,它提供一堆静态文件(如“/assets/”)。

在生产中,这些静态文件将由后端提供,但在开发中我们需要 ng serve 来填补这个空白。

直到现在我对文件名没有特殊要求,所以我需要做的就是在“资产”配置中声明一个新条目(在 angular.json 中)。

但现在我的应用程序需要访问一些文件,例如“content.json?__locale=pt”。在 ext4 文件系统上没有问题。但我是我团队中唯一从事 linux 工作的人;其他人正在 Windows 机器上工作,使用 NTFS,它禁止 '?'字符.

我正在考虑将文件存储为“content.json___locale=pt”,但我需要 ng serve 来重写传入的 url “content.json?__locale=pt”到“content.json___locale=pt”。

有什么办法吗?

我的最终解决方案有点老套,但我坚持了下来,因为它只影响本地开发,不影响生产代码。

因为我不想 ng eject,所以我选择使用 @angular-builders/custom-webpack:

$ yarn add @angular-builders/custom-webpack --dev

然后配置 serve 目标以使用此自定义生成器 (angular.json):

{
  ...
  "projects": {
    "myproject": {
      "projectType": "application",
      ...
      "architect": {
        ...
        "serve": {
          "builder": "@angular-builders/custom-webpack:dev-server",
          ...
        },
        ...
      }
    }
  },
  ...
}

由于 dev-server 构建器没有自己的 customWebpackConfiguration(我报告为 a feature request),我还配置了 build 目标来使用它自定义生成器:

{
  ...
  "projects": {
    "myproject": {
      "projectType": "application",
      ...
      "architect": {
        "build": {
          "builder": "@angular-builders/custom-webpack:browser",
          "options": {
            "customWebpackConfig": {
              "path": "./extra-webpack.config.ts"
            },
            ...
          },
          ...
        },
        ...
      }
    }
  },
  ...
}

最后,在 ./extra-webpack.config.ts 我做了一个小 express 魔术:

import { basename } from 'path';
import * as webpack from 'webpack';

export default {
  devServer: { before },
} as webpack.Configuration;

function before(app, server, compiler) {
  app.use('/cms', squash_question_mark);
}

function squash_question_mark(req, res, next) {
  const url = req.url.replace(/\?/g, '_');
  if (req.url !== url) {
    console.warn(`${basename(__filename)}: ${req.url} => ${url}`);
    req.url = url;
  }
  next();
}