如何在有/没有弹出创建反应应用程序的情况下压缩构建.还将压缩文件包含在脚本标记中,以索引.html



我正在使用react-scripts build来构建生产就绪的构建并将其部署到我正在使用

的 AWS 服务器上GENERATE_SOURCEMAP=false yarn build && aws s3 sync build/ s3://*********

有没有办法应用 gzip 压缩来构建文件并将 gzip 压缩的文件包含在索引中.html并将其部署到 aws 上,以便在浏览器中提供 gzip 文件。

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

"build": "react-scripts build && gzipper --verbose ./build"

并构建您的项目,您将获得 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;
        }

    }

您可以使用压缩-创建-反应-应用以最少的配置将构建后压缩添加到您的创建-反应-应用程序构建中。它使用brotli和gzip算法压缩构建文件夹中的所有html,css和javascript文件。

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

npm install compress-create-react-app --save-dev

然后在 package.json 中编辑 build 命令:

    "scripts": {
    "start": "react-scripts start",
-   "build": "react-scripts build",
+   "build": "react-scripts build && compress-cra",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  }

就是这样。构建应用时,应用将被压缩。

免责声明:我是压缩-创建-反应-应用程序的作者

我使用此命令将文件保持相同的名称

- yarn global add gzipper
- gzipper compress ./build ./gzip_build --output-file-format [filename].[ext] --verbose

仅供参考:gzipper --verbose给我一个错误。错过了"压缩"。

您也可以在

package.json中添加一个构建后脚本:

"postbuild": "find ./build -type f -name '*.css' -o -name '*.js' -exec gzip -k '{}' \;"

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

  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "postbuild": "node yourNodeGzipScript.js"   }

希望它能有所帮助。

最新更新