如何从"ng服务"提供静态目录

use*_*967 9 angular

我可以问一下webpack dev server config是否有类似的配置:

devServer : {
    historyApiFallback : true,
    stats : 'minimal',
    contentBase: helpers.root('../src/static'),
  }
Run Code Online (Sandbox Code Playgroud)

我想从静态目录提供静态文件,就像webpack开发服务器如何提供文件一样.谢谢

Rap*_*Rap 21

是肯定的.

在Angular应用程序的根目录中查找名为的文件angular.json.有一个名为"资产"的条目.在这里添加静态目录.他们下面的任何东西都将直接通过ng serve.当您上线时,所有这些文件都将被复制到/ dist目录,因此它们也将在生产环境中提供.

"projects": {
  "YourCoolProject": {
      "root": "",
      ...
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist",
            ...
            "assets": [
              "src/assets", 
              "myOtherStaticFiles"   /* <-- Add *your* directory(s) here */
            ],
            "styles": [
            ...
Run Code Online (Sandbox Code Playgroud)

ps是的,我知道你不能真正评论JSON.给我一个休息时间.

  • 我该如何调整资产以便在开发中使用资产,但不将其复制用于生产(在我的情况下,它们是通过不同的开发过程复制的)? (3认同)

Shy*_*oop 7

这个答案已经针对 Angular 8+ 进行了验证。如果您的静态文件位于 sourceDir 之外(在 angular.json 文件中查找),例如在 node_modules 中的某个位置,那么您需要添加类似这样的内容: angular.json 文件:

    root: "",
    architect: {
      build: {
        options:{
          outputPath: "dist/smartui",
          assets: {
            {
              "glob": "**/*",
              "input": "node_modules/@cruxcode/smartpdf",
              "output": "smartpdf/"
            }
          }
        }
      }
    }
Run Code Online (Sandbox Code Playgroud)

完成此操作后,每当您构建项目或使用 ngserve 时,资源都会input被复制到output您在 angular.json 文件中提到的内容,如上所示。一旦您构建或提供服务,该output目录就会出现在目录中。outputPath

glob在目录内匹配input

您的资产将在 处可用output/。在上面的示例中,我可以按如下方式访问代码中的资产 <img src="smartpdf/web/index.html">


Ari*_*nen 6

是的你可以。在 中angular.json,您可以使用名为 的条目assets。无论您在值数组中包含什么文件或目录assets,都将通过ng serve. 无论您添加什么,都将在所有projects/<your-project>/architect/build/options/assets构建配置中提供,并包含在生产构建目录中。dist

如果您希望某些内容仅在开发或测试期间可用,您可以使用构建配置projects/默认情况下,您有一个<your-project>部分/architect/build/configurations/production。因此,您可以添加自己的部分,例如../build/configurations/dev(也许最初复制production部分中的任何内容)。然后,您可以assets在那里添加条目。这些资产在生产配置中不可用。

要启动ng serve特定配置,请使用--configuration参数。例如,要匹配dev配置:

ng serve --configuration=dev
Run Code Online (Sandbox Code Playgroud)

免责声明:上面没有测试 - 只是阅读手册:-)