【问题标题】:Angular 5 production issueAngular 5生产问题
【发布时间】:2018-06-10 17:33:31
【问题描述】:

我正在尝试使用命令在 nginx 服务器上部署我的 Angular 5 应用程序

ng build --env=prod

但是当我访问我的网站时,供应商文件总是有错误。

当我使用以下命令在 /test 之类的文件夹中构建应用程序时,该应用程序运行良好:ng build --env=prod --bh /test/

我真的迷路了。是 nginx 的问题吗?

非常感谢。

【问题讨论】:

  • 您是否遇到与 ng serve --prod 相同的错误?
  • 我尝试使用 --prod 参数构建它。该网站正常显示,但 FormsModule 无法正常工作。这就是我使用环境参数的原因
  • 我没有要求构建,但服务:)
  • 抱歉。使用 serve --prod,我也不能使用 FormModule。并且没有创建文件。目的是使用 VestaCP 及其接口。所以我不能在那里运行 ng serve。

标签: angular deployment build


【解决方案1】:

您没有使用 -bh 选项指定文件夹。您指定基本 href。

当您想从根目录提供 angular 时,只需使用 -bh /。还要检查你的 index.html 是否有预定义的基本路径。

<base href="/">

【讨论】:

  • 即使使用命令,问题仍然出现 ng build --env=prod --bh /
  • SyntaxError: missing } after function body vendor.bundle.js:2:397750 和 Nginx 配置:pastebin.com/yFK7ynad
【解决方案2】:

Angular 默认使用 PathLocationStratergy,当您进行 prod 构建时,如果我们没有明确指定基本 href,它将无法使其工作。 如果您不想在这种情况下指定基本 href,则需要在路由中使用 HashLocationStratergy。

示例 RouterModule.forRoot(appRoutes, {useHash: true});

还有一个技巧 以下不是最佳做法 在您进行产品构建后,只需将 index.html 中的基本 href 更改为 "."

【讨论】:

    【解决方案3】:

    代替

    ng build --env=prod
    

    使用

    ng build --prod
    

    【讨论】:

      【解决方案4】:

      如果有人还在为 angular 2/4/5 app + Nginx 的生产设置而苦苦挣扎,那么这里是完整的解决方案:

      假设您想在 HOST:http://example.com 和 PORT:8080 上部署 Angular 应用 注意 - HOST 和 PORT 在您的情况下可能会有所不同。

      确保您的 index.html 头部标签中有 &lt;base href="/"&gt;

      1. 首先,转到您机器上的 Angular 存储库(即 /home/user/helloWorld)路径。

      2. 然后使用以下命令为您的生产服务器构建 /dist:

        ng build --prod --base-href http://example.com:8080

      3. 现在将 /dist(即 /home/user/helloWorld/dist)文件夹从您计算机的 Angular 存储库复制到您要托管生产服务器的远程计算机。

      4. 现在登录到您的远程服务器并添加以下 nginx 服务器配置。

        server {
        
            listen 8080;
        
            server_name http://example.com;
        
            root /path/to/your/dist/location;
        
            # eg. root /home/admin/helloWorld/dist
        
            index index.html index.htm;
        
            location / {
        
                try_files $uri $uri/ /index.html;
        
                # This will allow you to refresh page in your angular app. Which will not give error 404.
        
            }
        
        }
        
      5. 现在重启 nginx。

      6. 就是这样!现在您可以通过http://example.com:8080

      7. 访问您的 Angular 应用程序

      希望对您有所帮助。

      【讨论】:

      • 我会尽快尝试 :) !你对 apache 有什么想法吗?它只是将 / 重定向到 /index.html ?
      猜你喜欢
      • 2017-07-20
      • 2018-10-27
      • 2020-04-15
      • 2020-06-24
      • 1970-01-01
      • 1970-01-01
      • 2018-08-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多