Webpack gzip bundle - Uncaught SyntaxError: Unexpected token <

Viewed 1181

I am working on a react project using webpack for bundling. I wanted to reduce my bundle size so decided to use a compression plugin to serve a gzip file to get a nice small bundle size. The project builds fine and I get a nice small bundle size but here's my issues..when I go to serve my current project here is the error i get:

enter image description here

Looking into I realized that for whatever reason instead of serving the contents of main.js or vendor.js it's returning my index.html file

enter image description here

I am fairly certain my apache server is configured to handle gzip encoding this as I can see it in the response header:

enter image description here

Here is the webpack config I am using:

const appConstants = function() {
    switch (process.env.NODE_ENV) {
        case 'local':
            const localConfig = require('./config/local');
            return localConfig.config();
        case 'development':
            const devConfig = require('./config/development');
            return devConfig.config();
        case 'production':
        default:
            const prodConfig = require('./config/production');
            return prodConfig.config();
    }
};

const HtmlWebPackPlugin = require("html-webpack-plugin");
const webpack = require('webpack');
const CompressionPlugin = require('compression-webpack-plugin');


const htmlWebpackPlugin = new HtmlWebPackPlugin({
    template: "./src/index.html",
    filename: "./index.html",
    hash: true
});

const compressionPlugin = new CompressionPlugin({
    filename: "[path].gz[query]",
    test: /\.(js|css)$/,
    algorithm: 'gzip',
    deleteOriginalAssets: true
});

let webpackConfig = {
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader"
                }
            },
            {
                test: /\.css$/,
                exclude: [ /assets/, /node_modules/ ],
                use: [
                    {
                        loader: "style-loader"
                    },
                    {
                        loader: "css-loader",
                        options: {
                            modules: true,
                            importLoaders: 1,
                            localIdentName: "[name]_[local]_[hash:base64]",
                            sourceMap: true,
                            minimize: true
                        }
                    }
                ]
            },
            {
                test: /\.(pdf|jpg|png|gif|svg|ico)$/,
                exclude: [/node_modules/],
                use: [
                    {
                        loader: 'file-loader'
                    },
                ]
            },
            {
                test: /\.(woff|woff2|eot|ttf|svg)$/,
                exclude: [/node_modules/],
                use: {
                    loader: 'url-loader?limit100000'
                }
            }
        ]
    },
    entry: [ "@babel/polyfill", "./src/index.js"],
    output: {
        publicPath: appConstants().DS_BASENAME ? JSON.parse(appConstants().DS_BASENAME) : '/',
        chunkFilename: '[name].[chunkhash].js'
    },
    optimization: {
        splitChunks: {
            chunks: 'all',
        },
    },
    plugins: [
        htmlWebpackPlugin,
        compressionPlugin,
        new webpack.DefinePlugin({
            'process.env': appConstants()
        }),
        new webpack.EnvironmentPlugin(['NODE_ENV']),
    ],
    devServer: {
        historyApiFallback: true
    }
};

// configure source map per-env
if (process.env.NODE_ENV === 'local') {
    webpackConfig.devtool = 'source-map';
} else {
    webpackConfig.devtool = 'hidden-source-map';
}

module.exports = webpackConfig;

I cannot figure out why the gzip is not being read/recognized by the browser. I've tried several post with similar issues but no solutions.

1 Answers

You need to add middleware function to handle .js and .css file with suffix .gz Like that

const app = express()

app.get('*.js', function(req, res, next) {
  req.url = req.url + '.gz'
  res.set('Content-Encoding', 'gzip')
  res.set('Content-Type', 'text/javascript')
  next()
})

app.get('*.css', function(req, res, next) {
  req.url = req.url + '.gz'
  res.set('Content-Encoding', 'gzip')
  res.set('Content-Type', 'text/css')
  next()
})

app.use('/dist', serve('./dist', true))
app.use(express.static('./dist'));

You have to add middleware function before express.static

Good luck!

Related