Coder Social home page Coder Social logo

grunt-cache-breaker's Introduction

grunt-cache-breaker Build Status

<!-- Turn this -->
<script src="/js/dist/combined.min.js"></script>

<!-- into this -->
<script src="/js/dist/combined.min.js?rel=123456"></script>

<!-- or this -->
<script src="/js/dist/combined.min.123456.js"></script>

<!-- or this (md5 hash of file contents) -->
<script src="/js/dist/combined.min.ow23de343.js"></script>

Getting Started

This plugin requires Grunt ~0.4.1

If you haven't used Grunt before, be sure to check out the Getting Started guide, as it explains how to create a Gruntfile as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command:

npm install grunt-cache-breaker --save-dev

Once the plugin has been installed, add this to your Gruntfile.js

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

And then add one of the following to your list of tasks

##Usage ###(all examples require version 1.0.0 or above)

Append timestamps as query strings

Very useful in the development stages, not to be used in production though (see the other examples)

// Append a timestamp to 'all.min.js' & 'core.min.js' which are both located in 'index.html'
cachebreaker: {
    dev: {
        options: {
            match: ['all.min.js', 'core.min.css'],
        },
        files: {
            src: ['index.html']
        }
    }
}

Append timestamps as filename changes

A great idea if you have server rewrites. The file names are not changed, just changed in the markup.

File urls will be rewritten to all.min.4252425.js, for example

// Append a timestamp to 'all.min.js' & 'core.min.js' which are both located in 'index.html'
cachebreaker: {
    dev: {
        options: {
            match: ['all.min.js', 'core.min.css'],
            position: 'filename'
        },
        files: {
            src: ['index.html']
        }
    }
}

Append timestamps as filename changes in certain positions

Again, to be used with server rewrites, this allows you specify which 'piece' of the filename is rewritten.

File urls will be rewritten to all.4252425.js, for example.

// Append a timestamp to 'all.min.js' & 'core.min.js' which are both located in 'index.html'
cachebreaker: {
    dev: {
        options: {
            match: ['all.*.js', 'core.*.css'],
            position: 'overwrite'
        },
        files: {
            src: ['index.html']
        }
    }
}

##MD5 hash Use the contents of a file to generate a hash instead of a timestamp. Works in all positions mentioned above.

This example will create links like this: all.min.js?rel=hetweyj332 - which is useful as your templates only change when the contents of the file change.

// Append a md5 hash to 'all.js' which is located in 'index.html'
cachebreaker: {
    dev: {
        options: {
            match: ['all.js'],
            replacement: 'md5',
            src: {
                path: 'app/all.js'
            }
        },
        files: {
            src: ['index.html']
        }
    }
}

##Multiple MD5 hashs (v2.0.0 required) Use the contents of multiple files to generate a hash for each. NOTE: When passing an object to the match array like this, each key is the pattern to search for in the html file & the value is the actual file to be hashed.

If you're not sure, check the Gruntfile.js in this project for working examples.

// Append a md5 hash to 'all.js' & `script.js` which is located in 'index.html'
cachebreaker: {
    dev: {
        options: {
            match: [
                {
                    // Pattern    // File to hash
                    'script.js': 'test/fixtures/js/script.js',
                    'app.js':    'test/fixtures/js/app.js'
                }
            ],
            replacement: 'md5'
        },
        files: {
            src: ['index.html']
        }
    }
}

##Custom replacement You can also provide your own replacement if the Timestamps or MD5 hashes are not right for you.

This example would change the URL of app.js, to app.js?rel=v_2_0

// Append a custom string to 'all.js' which is located in 'index.html'
cachebreaker: {
    dev: {
        options: {
            match: ['all.js'],
            replacement: function (){
                return "v_2_0"
            }
        },
        files: {
            src: ['index.html']
        }
    }
}

Of course, as with all examples, you're free to mix & match the options. For example, you could use the custom method above, but to change the filename in the markup instead of a query string.

// Change filename in the markup to include custom string
cachebreaker: {
    dev: {
        options: {
            match: ['all.js'],
            position: 'filename',
            replacement: function (){
                return "v_2_0"
            }
        },
        files: {
            src: ['index.html']
        }
    }
}

##Options

Option Type Default Description
match string array null
replacement string function "time" "time", "md5", or custom function
position "string" "append" "append", "filename", "overwrite"
src.path "string" null Path to file to be used for md5 hash

Contributing

In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using Grunt.

grunt-cache-breaker's People

Contributors

shakyshane avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

grunt-cache-breaker's Issues

Encoding when reading/writing files

Foreign characters are getting convert when reading/writing. Would it help to have an option to set the encoding when reading/writing files like in grunt-cache-bust?

å -> Ã¥
ä -> ä
ö -> ö

options: {
    encoding: 'utf8',
}

jit-grunt: Plugin for the "cachebreaker" task not found.

When i start to build my code it shows

jit-grunt: Plugin for the "cachebreaker" task not found.
If you have installed the plugin already, please setting the static mapping.
See https://github.com/shootaroo/jit-grunt#static-mappings

Support cache-breaking for image tags as well

js/css cache-breaking totally rocks! it would be awesome to also have the possibility to cache-break image-tags as well!

img: {
  asset_url : '**/*.{png,jpg,gif}',
  file: 'index.php'
}

Replace ?rel=

Hi, I would like to have ability to replace ?rel= param to something different, for example ?v= etc.
Is it possible? Or can you add that possibility?

Can I see an example on how to use MD5 on multiple js files at once?

I know i'm probably totally off here.. but this is what i'm trying to do:

cachebreaker: {
        dev: {
            options: {
                match: ['vendors.js', 'app.js', 'directives.js' , 'services.js', 'controllers.js'],
                replacement: 'md5',
                src: {
                    path: [ 
                            '../scripts_final/vendors.js', 
                            '../scripts_final/app.js', 
                            '../scripts_final/directives.js', 
                            '../scripts_final/services.js', 
                            '../scripts_final/controllers.js', 
                          ]
                }
            },
            files: {
                src: ['../index.html']
            }
        }

What am I doing wrong?

Not workig

Sorry, but it's not working for me. I guess it should make application.min.js with md5 hash in filename when I run grunt build? In my case everything is same like before I installed your plugin.

doesnt work when assets are in subdir

Take this config:

        cachebreaker: {
            dev: {
                options: {
                    match: ['app/dist/built.*.js'],
                    position: 'overwrite'
                },
                files: {
                    src: ['app/index.html']
                }
            }
        }

and in my index.html i have:

<script src="dist/built.min.js"></script>

Running cache-breaker with this config will not make any modification to the index.html or the built.min.js file.

This happens cause cache-breaker is looking for the string app/dist/built.min.js in the index.html file, but it is just dist/built.min.js.

Cinfiguration

Maybe its not an issue but I cant setup cache breaker because I don't know where to put this configuration:

// Append a md5 hash to 'all.js' which is located in 'index.html'
cachebreaker: {
dev: {
options: {
match: ['all.js'],
replacement: 'md5',
src: {
path: 'app/all.js'
}
},
files: {
src: ['index.html']
}
}
}

I tried in gruntfile.js and have an error

NODE_ENV=production grunt build

/home/projects/gruntfile.js:140
cachebreaker: {
^^^^^^^^^^^^
Loading "gruntfile.js" tasks...ERROR

SyntaxError: Unexpected identifier
Warning: Task "build" not found. Use --force to continue.

Aborted due to warnings.

Appends query string to type="text/css"

Using this plugin also appends the query parameter in type="text/css" resulting in

This does not allow the file to load in the browser.

My configs are as below

module.exports = function(grunt){

//configuration
grunt.initConfig({
    cachebreaker: {
    	dev: {
        	options: {
            	match: ['css/*'],
            	replacement: function (){
                return new Date().getTime()
            	}
        	},
       		 files: {
            	src: ['template/*']
        	}
    	}
	}
})

//load the plugin
grunt.loadNpmTasks('grunt-cache-breaker');

//registering the task
grunt.registerTask('default',['cachebreaker']);

};

MD5 Hash in filename is not updated

When a Key-Value-Mapping is passed as a parameter for match and "filename" mode is used, the replacement in the html files only works for the first run, when an exact match for the original filename was found.

gruntfile:

cachebreaker: {
			dev: {
				options: {
					match: [
						{
						'script.min.js': '../js/script.min.js'
						}
					],
					position: 'filename',
					replacement: 'md5'
				},
				files: {
					src: ['../templates/header.tpl','../templates/footer.tpl']
				}
			}
        }

For the first run, this code fragment in tpl files:

[..]
<script type="text/javascript" src="{$JS}script.min.js"></script>
[..]

is correctly changed to this:

[..]
<script type="text/javascript" src="{$JS}script.min.de94ef7c57.js"></script>
[..]

But afterwards it is not updated anymore for subsequent runs.

(This {$JS} is used for the templating engine but removing it does not make any difference)

Pages with hash tag

In a html page, I have a link index.html#/profile , when I run grunt this is not being replaced with index.html?rel=1kj08da#/profile

Can you please update the code even with that case.

Custom matching regex

If we could specify our own complete regex for matching it would make it more powerful.

Custom replacement with grunt variable

How can I leverage using a grunt variable for custom replacement. I am looking to add svn revision number to the query string, eg:

grunt.initConfig({
  svn_info: {
    app: '.'
  },
  cachebreaker: {
    dev: {
      options: {
        match: ['ax-main.js', 'ax-main.min.js', 'ax.css'],
        replacement: function (){
          return '<%= svn_info.app.last_revision %>_' ;
        }
      },
      files: {
        src: [
          'deploy/modules/includes/app/header/header.php',
          'deploy/modules/includes/app/header/header_localization.php',
          'deploy/modules/includes/app/header/header_loggedout.php',
          'deploy/modules/includes/app/header/header_login.php'
        ]
      }
    }
  },
});

Timestamp Not Working

I'm trying to have a timestamp at the end of my file, in this format file.css?v=20151123120000. My cachebreaker config looks like this:

cachebreaker: {
  dev: {
    options: {
        match: [
          'main.css',
        ],
        replacement: function () {
            return "?v=";
        }
    },
    files: {
        src: ['/index.html']
    }
  }
}

Am I doing something wrong. Any help is appreciated. Thanks in advance!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.