如何在不弹出 create-react-app 的情况下压缩构建。还将压缩文件包含到 index.html 中的脚本标记中

har*_*mar 6 reactjs create-react-app

我正在使用react-scripts build生产就绪构建并将其部署在我正在使用的 AWS 服务器上

GENERATE_SOURCEMAP=false yarn build && aws s3 sync build/ s3://*********

有什么方法可以应用 gzip 压缩来构建文件并将 gzip 压缩文件包含到 index.html 中并将其部署在 aws 上,以便在浏览器中 gzipped 文件将送达。

小智 13

安装 gzipper 包 ( https://www.npmjs.com/package/gzipper )。像这样修改构建命令

"build": "react-scripts build && gzipper --verbose ./build"
Run Code Online (Sandbox Code Playgroud)

并构建您的项目,您将同时获得 gzip 和常规文件。由您决定让服务器提供 gzip 而不是常规文件。如果你使用 nginx,你必须在 nginx.conf 文件中设置你的服务器,如下所示

server {
        # Gzip Settings
        gzip on;
        gzip_static on; # allows pre-serving of .gz file if it exists 
        gzip_disable "msie6"; # Disable for user-agent Internet explorer 6. Not supported.
        gzip_proxied any; # enable gzip for all proxied requests
        gzip_buffers 16 8k; # number and size of buffers to compress a response
        gzip_http_version 1.1;
        gzip_min_length 256; # Only gzip files of size in bytes
        gzip_types text/plain text/css text/html application/javascript application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/vnd.ms-fontobject application/x-font-ttf font/opentype image/svg+xml image/x-icon;
        gunzip on; # Uncompress on the fly
        listen       4000;
        server_name  localhost;



        location / {
            root   html/react-app;
            index  index.html index.htm;
        }


        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }


    }
Run Code Online (Sandbox Code Playgroud)

  • 您应该添加“compress”来压缩命令将是:“react-scripts build && gzipper compress --verbose ./build” (2认同)

小智 7

您可以使用compress-create-react-app 以最少的配置将构建后压缩添加到 create-react-app构建中。它使用 brotli 和 gzip 算法压缩构建文件夹中的所有 html、css 和 javascript 文件。

首先将其安装为开发依赖项:

npm install compress-create-react-app --save-dev
Run Code Online (Sandbox Code Playgroud)

然后编辑 package.json 中的构建命令:

    "scripts": {
    "start": "react-scripts start",
-   "build": "react-scripts build",
+   "build": "react-scripts build && compress-cra",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  }
Run Code Online (Sandbox Code Playgroud)

就是这样。您的应用程序在构建时将被压缩。

免责声明:我是 compress-create-react-app 的作者


Nil*_*Nil 1

更改 cra 构建过程并不容易,您可以将其弹出,但之后您必须创建自己的过程。但是,在 package.json 中,您可以定义要在构建后启动的任务:

  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "postbuild": "node yourNodeGzipScript.js"   }
Run Code Online (Sandbox Code Playgroud)

希望它能有所帮助。