Help us understand the problem. What is going on with this article?

CSSやJSのキャッシュ対策をGruntで行う

More than 5 years have passed since last update.

目的

システムをアップデート時にCSSやJavascriptを更新していると,ブラウザのキャッシュが効いていて思った挙動にならなく困ったりします.
対策としては下記のようにCSS, JSのsrcにビルド時のタイムスタンプなどをQueryStringとして設定して強制的にリクエストを呼ばせます.

<link href="/css/main.css?rel=20141020" rel="stylesheet" type="text/css"/>

QueryStringをビルド時に動的につける方法は様々あるのですが,今回はGruntを使ってやってみました.

方法

grunt-cache-breakerといういい感じにQueryStringを追加してくれるPluginがあるので,使います.

Gruntfile.js

var moment = (require('moment'))();

module.exports = function (grunt) {

  var timestamp = 'None';

  grunt.initConfig({
    cachebreaker: {
      dist: {
        options: {
            match: [
              '.css',
              '.js'
            ],
            replacement: function () {
              return moment.format('YYYYMMDD');
            }
        },
        files: {
          src: [
            'build/**/WEB-INF/view/**/*.jsp'
          ]
        }
      }
    }
  });

  grunt.loadNpmTasks('grunt-cache-breaker');

  grunt.task.registerTask('default', ['cachebreaker:dist']);
};

package.json

{
  "name": "package",
  "version": "0.0.1",
  "devDependencies": {
    "grunt": "^0.4.5",
    "moment": "^2.8.3",
    "grunt-cache-breaker": "^1.0.1"
  }
}

使い方

$ npm install
$ grunt
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away