使用 react-snap 预渲染带有压缩 (gzip) 源的 React 应用程序

Prerendering React app with compressed (gzip) sources with use of react-snap

我正在尝试使用 react-snap 预呈现我的 react 应用程序。我的项目没有使用 create-react-app.

// react-snap configuration
{
    inlineCss: true,
    source: "dist",
    skipThirdPartyRequests: true
}

如果我使用 webpack mode: development 构建我的应用程序,预渲染工作正常。但是当我使用我的生产版本时它不会。调试了一段时间后,发现只有在使用compression-webpack-plugin时才会出现这个问题。当我把它评论出来时,它成功完成了。

/// webpack.config.prod.babel.js

/* eslint-disable import/default */
import merge from 'webpack-merge';
import CompressionPlugin from 'compression-webpack-plugin';

import common from './webpack.config.common.babel';

module.exports = (env = {}) => {
    return merge(common(env), {
        mode: 'production',
        devtool: 'nosources-source-map',
        plugins: [
            /* when I uncomment the use of plugin, the prerendering stops to work */
            // new CompressionPlugin({
            //     algorithm: 'gzip',
            //     compressionOptions: {level: 9},
            //     test: /\.css$|\.js$|\.map|\.svg|\.woff|\.woff2|\.ttf|\.eot$/,
            //     threshold: 2 * 1024,
            //     deleteOriginalAssets: true
            // })
        ]
    });
};

react-snap报错: pageerror at /: SyntaxError: Unexpected token '<'

我发现,它会尝试获取我构建的 mainvendor javascript 扩展名为 .min.js 的文件。但是在我的构建中,只有扩展名为 .min.js.gz 的文件可以通过浏览器的标准请求成功处理。

我的生产版本无需预渲染即可正常工作。所以我想这是一些 react-snap 配置的问题,但我没有找到任何解决方案。

完全可以使用 react-snap 和 gzipped 源吗?

有一个 deleteOriginalAssets: true 选项,没有它 CompressionPlugin 应该保留原始 .min.js 文件供您与 react-snap 一起使用。虽然您的服务器将继续为浏览器提供 .min.js.gz 文件,因为它们仍然存在。