在React服务器中提供gzip文件 [英] Serving gzip files in React server

查看:233
本文介绍了在React服务器中提供gzip文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在React中实际提供我的bundle.js文件的gzip压缩时遇到了麻烦。我试图大幅度减小这个尺寸,我已经完成了uglify和重复数据删除等等......它从2.9mb下降到2.6mb这对我来说真的很奇怪。我现在使用压缩插件,我得到一个输出的gzip文件,但现在我仍在服务bundle.js而不是bundle.js.gz。

I'm having trouble actually serving a gzip compression of my bundle.js file in React. I am trying to reduce the size of this dramatically, and I have done uglify and dedupe, etc ... and it's gone down from 2.9mb to 2.6mb which is really weird to me. I am now using the compression plugin and I get an outputted gzip file, but now I'm still serving the bundle.js and not the bundle.js.gz.

我不想使用express中的压缩中间件,因为我在构建过程中使用gzip。无论如何,这是我的distServer文件:

I don't want to use the compression middleware from express, because I'm doing the gzip in the build process. Anyways, here is my distServer file:

import express from 'express';
import path from 'path';
import open from 'open';

/* eslint-disable no-console */

const port = process.env.PORT || 3000;
const app = express();


app.use(express.static('dist'));

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.get('*', function(req, res) {
  res.sendFile(path.join( __dirname, '../dist/index.html'));
});

app.listen(port, function(err) {
  if (err) {
    console.log(err);
  } else {
    open(`http://localhost:${port}`);
  }
});

我的webpack配置是:

And my webpack config is:

import webpack from 'webpack';
import path from 'path';
import ExtractTextPlugin from 'extract-text-webpack-plugin';

var CopyWebpackPlugin = require('copy-webpack-plugin');
var CompressionPlugin = require("compression-webpack-plugin");
var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

export default {
  devtool: 'source-map',
  noInfo: false,
  entry: [
    './src/index'
  ],
  target: 'web',
  output: {
    path: __dirname + '/dist', // Note: Physical files are only output by the production build task `npm run build`.
    publicPath: '/',
    filename: 'bundle.js'
  },
  plugins: [
    // new BundleAnalyzerPlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.DefinePlugin({
      'process.env': {NODE_ENV: '"production"'}
    }),
    new ExtractTextPlugin('styles.css'),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin({
      mangle: true,
      compress: {
        warnings: false, // Suppress uglification warnings
        pure_getters: true,
        unsafe: true,
        unsafe_comps: true,
        screw_ie8: true
      },
      output: {
        comments: false,
      },
      exclude: [/\.min\.js$/gi] // skip pre-minified libs
    }),
    new CopyWebpackPlugin([
      { from: 'src/robots.txt', to: 'robots.txt' },
      { from: 'src/sitemap.xml', to: 'sitemap.xml' }
    ], {
      copyUnmodified: true
    }),
    new webpack.IgnorePlugin(/^\.\/locale$/, [/moment$/]),
    new CompressionPlugin({
      asset: "[path].gz[query]",
      algorithm: "gzip",
      test: /\.js$|\.css$|\.html$/,
      threshold: 10240,
      minRatio: 0
    })
  ],
  module: {
    loaders: [
      {test: /\.js$/, include: path.join(__dirname, 'src'), loaders: ['babel']},
      {test: /(\.css)$/, loader: ExtractTextPlugin.extract("css?sourceMap")},
      {test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file'},
      {test: /\.(woff|woff2)$/, loader: 'url?prefix=font/&limit=5000'},
      {test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream'},
      {test: /\.(jpe?g|png|gif|svg)$/i, loader: "url?limit=10000"},
      {test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=image/svg+xml'},
      {
        test: /favicon\.ico$/,
        loader: 'url',
        query: {
          limit: 1,
          name: '[name].[ext]',
        },
      }
    ]
  }
};

我认为app.get函数会根据需要引入这些gzip文件,但我可能会丢失一步?另外,在我的index.html文件中,是否需要省略一起引入捆绑文件的脚本标记?

I thought the app.get functions would bring in those gzip files as needed, but I might be missing a step? Also, in my index.html file, do I need to omit the script tag bringing in the bundle file all together?

任何指导和想法都将不胜感激!

Any guidance and thoughts would be appreciated!

推荐答案

您应该将静态列表放在中间件之后

You should put your static listing after the middleware

import express from 'express';
import path from 'path';
import open from 'open';

/* eslint-disable no-console */

const port = process.env.PORT || 3000;
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(express.static('dist'));

app.get('*', function(req, res) {
  res.sendFile(path.join( __dirname, '../dist/index.html'));
});

app.listen(port, function(err) {
  if (err) {
    console.log(err);
  } else {
    open(`http://localhost:${port}`);
  }
});

这篇关于在React服务器中提供gzip文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆