user1933888
user1933888

Reputation: 3037

angular2 disable browser caching

I am using angular2 for web development, and Jenkins for continuous integration, when i release code at the end of every sprint, it gets deployed on CI Server.

But, when users load the UI, they do not get the new UI changes by default, they have to clear the cache ( I do not want users to clear the cache or disable there cache just for this UI)

How can I handle programatically for the browser to not cache old files and reload the new changes by default (atleast in development)

Note: I presently set:

import { enableProdMode } from '@angular/core';
enableProdMode();

None of the documentation states this to be the reason and removing it does not help either.

Upvotes: 3

Views: 4505

Answers (2)

julianpoemp
julianpoemp

Reputation: 2042

I fixed it using a special .htaccess file. Just uncomment the "BROWSER CACHING" part: https://gist.github.com/julianpoemp/bcf277cb56d2420cc53ec630a04a3566

Upvotes: 0

dmungin
dmungin

Reputation: 812

Two popular ways of accomplishing this "cache busting" are:

  1. Using a query string on the end of your file request that gives a version number. For example, when you create a javascript file you would name it "my-file.js". Then in your HTML you would request it as:

<script type="text/javascript" src="my-file.js?v=1.0.0"></script>

When you make some changes to your file you update your request to:


<script type="text/javascript" src="my-file.js?v=1.0.1"></script>

You can use whatever query string you want as long as you change it. The browser sees it as a different file, but it should have no effect on what file your server sends as a response.

  1. If you are using a bundler like webpack or systemJS they can automatically include a hash as part of the file name. This hash can change based on the file contents so that when the contents change the file name changes and thus the file is no longer cached. The caveat with this is that you need to update the file name you are requesting in your HTML. Again, most tools have a way to automatically do this for you.

A webpack example config to accomplish this is:

output: {
        path: 'dist',
        publicPath: '/',
        filename: 'js/[name].[chunkhash].js'
    },

and then use the HtmlWebpackPlugin to auto-generate your index.html with the correct file names injected (with inject: true):

 plugins: [
            new HtmlWebpackPlugin({
                filename: '../index.html',
                template: './index.html',
                inject: true
            }), ...

More info on webpack file naming:

https://github.com/webpack/docs/wiki/Configuration#output

More info on html webpack plugin:

https://github.com/ampedandwired/html-webpack-plugin#basic-usage

Upvotes: 3

Related Questions