Angular2:在生产中使用 gzip 文件

Angular2: using gzip files in production

我正在使用 angular-cli 来编译我的应用程序。当 运行 ng build --prod 创建了 gzip 包文件,但 index.html 仍在使用完整大小的文件。我尝试了 运行 ng build --prod --aot 并得到了相同的结果。我如何告诉 angular-cli 在生产中使用 .gz 文件?

您使用的是旧版本的 CLI:最新版本不再生成 gzip 文件。

要提供 gzip 文件,浏览器必须发送一个带有 header 的请求,告知它接受 gzip 响应,并且服务器必须配置为 gzip 文件(或加载已经 gzip 的文件),并在浏览器请求文件时发送 gzip 压缩结果。

如何操作取决于您的服务器。

但是 index.html 从不引用 gzip 文件。它指的是JS文件。浏览器向服务器请求一个 JS 文件并告诉服务器它接受 gzip 压缩的响应,并且服务器发回 gzip 压缩的 JS 文件,如果它已被配置为这样做的话。

如果您在 AWS 上托管网站,则无需自行压缩。我正在使用 Cloud Front (CDN),它为我做了一切。

如何在 Cloud Front 中启用 Gzip 压缩?

在设置 Cloud Front Distribution 时将 'Compress Objects Automatically' 从否更改为是

更多详情: https://aws.amazon.com/blogs/aws/new-gzip-compression-support-for-amazon-cloudfront/

我创建这个主要是为了测试目的,但是如果你想要一个简单的 Express.js 服务器到 运行 应用程序

  1. https://angular.io/tutorial/toh-pt0

  2. ng build 构建生产文件

  3. npm install express compression path --save

  4. dist/[project-name] 中创建 server.js 并添加:

     const express = require("express");
     const compression = require('compression'); // <--
     const path = require('path');
     const app = express();
    
     app.use(compression()); // <--
    
     app.get("/", (req, res) => {
       res.sendFile(path.join(__dirname, '/index.html'));
     });
    
     app.use(express.static('.'))
    
     const PORT = process.env.PORT || 8080;
     app.listen(PORT, () => {
       console.log(`Server is running http://127.0.0.1:${PORT}/`);
     });
    
  5. cd dist/[项目名称]

  6. node server.js