0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Expressでgzipファイルを送信する(Rewrite)

Last updated at Posted at 2017-01-24

前提

・記載例の対象はjsファイルのみ
・gzipファイルはあらかじめ用意しておく

1. gzipファイルを用意する

ここのやり方は任意です。
参考程度ですが、
・gulpを使う場合 -> gulp-gzip
・webpackを使う場合 -> compression-webpack-plugin
というライブラリを使うと簡単にできました。

gulp-gzip

gulpfile.babel.js
gulp.task('gzip:js', () => {
  return gulp.src(`<inputのパス>/+(foo|bar|baz)*.js`)
  .pipe(gzip())
  .pipe(gulp.dest(<outputのパス>);
});

compression-webpack-plugin

webpack.config.babel.js
new CompressionPlugin({
  asset: '[path].gz[query]',
  algorithm: 'gzip',
  test: /\.js$/,
  threshold: 10240,
  minRatio: 0.8
})

2. Expressでリクエストをハンドリングする

app.js
// jsファイルのリクエストをハンドリング
app.get(/(foo|bar|baz).*\.(js)$/, (req, res, next) => {
  req.url = `${req.url}.gz`;
  res.set('Content-Encoding', 'gzip');
  next();
});

ハンドリング自体はこれでできるのですが、
このままだと、

MIME タイプの不一致により “foo.js” からのリソースがブロックされました (X-Content-Type-Options: nosniff)。

というエラーになってしまいます(上記はFirefoxのコンソール)。

'Content-Type'が'application/octet-stream'になっているので、
明示的に'application/javascript'を指定してあげると上記のエラーは出なくなります。

app.js
app.get(/(foo|bar|baz).*\.(js)$/, (req, res, next) => {
  req.url = `${req.url}.gz`;
  res.set('Content-Type', 'application/javascript'); <- この行を追加
  res.set('Content-Encoding', 'gzip');
  next();
});

3. 動作確認

throttlingをRegular 4Gにした場合だと、手元ではこのくらい変わりました。
圧縮前
before.png

圧縮後
after.png

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?