You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
To enable long-term caching of static resources produced by webpack:
9
10
10
11
1. Use `[chunkhash]` to add a content-dependent cache-buster to each file.
11
-
2. Use compiler stats to get the file names when requiring resources in HTML.
12
-
3. Generate the chunk-manifest JSON and inline it into the HTML page before loading resources.
13
-
4. Ensure that the entry point chunk containing the bootstrapping code doesn’t change its hash over time for the same set of dependencies.
12
+
2. Extract the webpack manifest into a separate file.
13
+
3. Ensure that the entry point chunk containing the bootstrapping code doesn’t change hash over time for the same set of dependencies.
14
+
15
+
For even more optimized setup:
16
+
4. Use compiler stats to get the file names when requiring resources in HTML.
17
+
5. Generate the chunk manifest JSON and inline it into the HTML page before loading resources.
18
+
14
19
15
20
## The problem
16
21
17
22
Each time something needs to be updated in our code, it has to be re-deployed on the server and then re-downloaded by all clients. This is clearly inefficient since fetching resources over the network can be slow. This is why browsers cache static resources.
18
23
19
-
The way it works has a pitfall: if we don’t change filenames of our resources when deploying a new version, browser might think it hasn’t been updated and client will get a cached version of it.
24
+
The way it works has a pitfall: If we don’t change filenames of our resources when deploying a new version, the browser might think it hasn’t been updated and client will get a cached version of it.
20
25
21
-
Probably the simplest way to tell the browser to download a newer version is to alter asset’s file name. In a pre-webpack era we used to add a build number to the filenames as a parameter and then increment it:
26
+
A simple way to tell the browser to download a newer version is to alter the asset’s file name. In a pre-webpack era we used to add a build number to the filenames as a parameter and then increment it:
22
27
23
28
```bash
24
29
application.js?build=1
25
30
application.css?build=1
26
31
```
27
32
28
-
It is even easier to do with webpack: each webpack build generates a unique hash which can be used to compose a filename. The following example config will generate 2 files (1 per entry point) with a hash in filenames:
33
+
It is even easier to do with webpack. Each webpack build generates a unique hash which can be used to compose a filename, by including output [placeholders](/concepts/output/#options).
34
+
The following example config will generate 2 files (1 per entry) with hashes in filenames:
29
35
30
36
```js
31
37
// webpack.config.js
32
-
constpath=require('path');
38
+
constpath=require("path");
33
39
34
40
module.exports= {
35
41
entry: {
36
-
vendor:'./src/vendor.js',
37
-
main:'./src/index.js'
42
+
vendor:"./src/vendor.js",
43
+
main:"./src/index.js"
38
44
},
39
45
output: {
40
-
path:path.join(__dirname, 'build'),
41
-
filename:'[name].[hash].js'
46
+
path:path.join(__dirname, "build"),
47
+
filename:"[name].[hash].js"
42
48
}
43
49
};
44
50
```
45
51
46
52
Running webpack with this config will produce the following output:
47
53
48
54
```bash
49
-
Hash: 55e783391098c2496a8f
50
-
Version: webpack 1.10.1
51
-
Time: 58ms
52
-
Asset Size Chunks Chunk Names
53
-
main.55e783391098c2496a8f.js 1.43 kB 0 [emitted] main
main.2a6c1fee4b5b0d2c9285.js 2.57 kB 1 [emitted] main
61
+
[0] ./src/index.js 63 bytes {1} [built]
62
+
[1] ./src/vendor.js 63 bytes {0} [built]
57
63
```
58
64
59
-
But the problem here is that, *each* time we create a new build, all filenames will get altered and clients will have to re-download the whole application code again. So how can we guarantee that clients always get the latest versions of assets without re-downloading all of them?
65
+
But the problem here is, builds after *any file update* will update all filenames and clients will have to re-download all application code. So how can we guarantee that clients always get the latest versions of assets without re-downloading all of them?
60
66
61
67
## Generating unique hashes for each file
62
68
63
-
What if we could produce the same filename if the contents of the file did not change between builds? For example, the file where we put all our libraries and other vendor stuff does not change that often.
64
-
65
-
T> Separate your vendor and application code with [CommonsChunkPlugin](/plugins/commons-chunk-plugin) and create an explicit vendor chunk to prevent it from changing too often.
69
+
What if we could produce the same filename, if the contents of the file did not change between builds? For example, it would be unnecessary to re-download a vendor file, when no dependencies have been updated, only application code.
66
70
67
-
Webpack allows you to generate hashes depending on the file contents. Here is the updated config:
71
+
webpack allows you to generate hashes depending on file contents, by replacing the placeholder `[hash]` with `[chunkhash]`. Here is the updated config:
68
72
69
-
```js
70
-
// webpack.config.js
73
+
```diff
71
74
module.exports = {
72
75
/*...*/
73
76
output: {
74
77
/*...*/
75
-
filename:'[name].[chunkhash].js'
78
+
- filename: "[name].[hash].js"
79
+
+ filename: "[name].[chunkhash].js"
76
80
}
77
81
};
78
82
```
79
83
80
84
This config will also create 2 files, but in this case, each file will get its own unique hash.
81
85
82
86
```bash
83
-
main.155567618f4367cd1cb8.js 1.43 kB 0 [emitted] main
main.70b594fe8b07bcedaa98.js 2.57 kB 1 [emitted] main
93
+
[0] ./src/index.js 63 bytes {1} [built]
94
+
[1] ./src/vendor.js 63 bytes {0} [built]
85
95
```
86
96
87
97
T> Don’t use [chunkhash] in development since this will increase compilation time. Separate development and production configs and use [name].js for development and [name].[chunkhash].js in production.
88
98
89
-
W> Due to this [issue in Webpack](https://github.com/webpack/webpack/issues/1315), this method of generating hashes still isn’t deterministic. To ensure hashes are generated based on the file contents, use [webpack-md5-hash plugin](https://github.com/erm0l0v/webpack-md5-hash). Here is an example how to integrate it into your project: https://github.com/okonet/webpack-long-term-cache-demo/pull/3/files
90
-
91
99
## Get filenames from webpack compilation stats
92
100
93
-
When working in development mode, you just reference a JavaScript file by entry point name in your HTML.
101
+
When working in development mode, you just reference JavaScript files by entry point name in your HTML.
94
102
95
103
```html
104
+
<scriptsrc="vendor.js"></script>
96
105
<scriptsrc="main.js"></script>
97
106
```
98
107
99
108
Although, each time we build for production, we’ll get different file names. Something, that looks like this:
In order to reference a correct file in the HTML, we’ll need some information about our build. This can be extracted from webpack compilation stats by using this simple plugin:
115
+
In order to reference a correct file in the HTML, we’ll need information about our build. This can be extracted from webpack compilation stats by using this plugin:
106
116
107
117
```js
108
118
// webpack.config.js
109
-
constpath=require('path');
119
+
constpath=require("path");
110
120
111
121
module.exports= {
112
122
/*...*/
113
123
plugins: [
114
124
function() {
115
125
this.plugin("done", function(stats) {
116
126
require("fs").writeFileSync(
117
-
path.join(__dirname, "…", "stats.json"),
127
+
path.join(__dirname, "build", "stats.json"),
118
128
JSON.stringify(stats.toJson()));
119
129
});
120
130
}
@@ -127,7 +137,7 @@ Alternatively, just use one of these plugins to export JSON files:
A sample output of webpack-manifest-plugin for our config looks like:
140
+
A sample output when using `webpack-manifest-plugin` in our config looks like:
131
141
132
142
```json
133
143
{
@@ -136,30 +146,36 @@ A sample output of webpack-manifest-plugin for our config looks like:
136
146
}
137
147
```
138
148
139
-
The rest depends on your server setup. There is a nice [walk through for Rails-based projects](http://clarkdave.net/2015/01/how-to-use-webpack-with-rails/#including-precompiled-assets-in-views). For serverside rendering in Node.js you can use [webpack-isomorphic-tools](https://github.com/halt-hammerzeit/webpack-isomorphic-tools). Or, if your application doesn’t rely on any server-side rendering, it’s often enough to generate a single `index.html` file for your application. To do so, just use these 2 amazing plugins:
To minimize the size of generated files, webpack uses identifiers instead of module names. During compilation, identifiers are generated, mapped to chunk filenames and then put into a JavaScript object called *chunk manifest*.
152
+
To generate identifiers that are preserved over builds, webpack supply the `NamedModulesPlugin` (recommended for development) and `HashedModuleIdsPlugin` (recommended for production).
143
153
144
-
It will simplify the setup dramatically.
154
+
> TODO: When exist, link to `NamedModulesPlugin` and `HashedModuleIdsPlugin` docs pages
145
155
146
-
We’re done, you might think. Well, almost.
156
+
> TODO: Describe how the option `recordsPath` option works
147
157
148
-
## Deterministic hashes
158
+
The chunk manifest (along with bootstrapping/runtime code) is then placed into the entry chunk and it is crucial for webpack-packaged code to work.
149
159
150
-
To minimise the size of generated files, webpack uses identifiers instead of module names. During compilation identifiers are generated, mapped to chunk filenames and then put into a JavaScript object called *chunk manifest*. It is (along with some bootstrapping code) then placed into the entry chunk and it is crucial for webpack-packaged code to work.
160
+
T> Separate your vendor and application code with [CommonsChunkPlugin](/plugins/commons-chunk-plugin)and create an explicit vendor chunk to prevent it from changing too often. When `CommonsChunkPlugin` is used, the runtime code is moved to the *last* common entry.
151
161
152
-
The problem with this is the same as before: whenever we change any part of the code, it will, even if the rest of its contents wasn’t altered, update our entry chunk to include the new manifest. This, in turn, will lead to a new hash and dismiss the long-term caching.
162
+
The problem with this, is the same as before: Whenever we change any part of the code it will, even if the rest of its contents wasn’t altered, update our entry chunk to include the new manifest. This in turn, will lead to a new hash and dismiss the long-term caching.
153
163
154
-
To fix that, we should use [chunk-manifest-webpack-plugin](https://github.com/diurnalist/chunk-manifest-webpack-plugin) which will extract that manifest to a separate JSON file. Here is an updated webpack.config.js which will produce chunk-manifest.json in our build directory:
164
+
To fix that, we should use [chunk-manifest-webpack-plugin](https://github.com/diurnalist/chunk-manifest-webpack-plugin), which will extract the manifest to a separate JSON file. This replaces the chunk manifest with a variable in the webpack runtime. But we can do even better; we can extract the runtime into a separate entry by using `CommonsChunkPlugin`. Here is an updated `webpack.config.js` which will produce the manifest and runtime files in our build directory:
155
165
156
166
```js
157
167
// webpack.config.js
158
-
var ChunkManifestPlugin =require('chunk-manifest-webpack-plugin');
168
+
var ChunkManifestPlugin =require("chunk-manifest-webpack-plugin");
Since we removed the manifest from entry chunk, now it’s our responsibility to provide webpack with it. You have probably noticed the `manifestVariable` option in the example above. This is the name of the global variable where webpack will look for the manifest JSON and this is why *it should be defined before we require our bundle in HTML*. This is easy as inlining the contents of the JSON in HTML. Our HTML head section should look like this:
187
+
As we removed the manifest from the entry chunk, now it’s our responsibility to provide webpack with it. The `manifestVariable` option in the example aboveis the name of the global variable where webpack will look for the manifest JSON. This *should be defined before we require our bundle in HTML*. This is achieved by inlining the contents of the JSON in HTML. Our HTML head section should look like this:
@@ -184,32 +200,33 @@ Since we removed the manifest from entry chunk, now it’s our responsibility to
184
200
</html>
185
201
```
186
202
187
-
So the final webpack.config.js should look like this:
203
+
At the end of the day, the hashes for the files should be based on the file content. For this use [webpack-chunk-hash](https://github.com/alexindigo/webpack-chunk-hash) or [webpack-md5-hash](https://github.com/erm0l0v/webpack-md5-hash).
204
+
205
+
So the final `webpack.config.js` should look like this:
188
206
189
207
```js
190
-
var path =require('path');
191
-
var webpack =require('webpack');
192
-
var ManifestPlugin =require('webpack-manifest-plugin');
193
-
var ChunkManifestPlugin =require('chunk-manifest-webpack-plugin');
194
-
var WebpackMd5Hash =require('webpack-md5-hash');
208
+
var path =require("path");
209
+
var webpack =require("webpack");
210
+
var ChunkManifestPlugin =require("chunk-manifest-webpack-plugin");
211
+
var WebpackChunkHash =require("webpack-chunk-hash");
T> If you're using [webpack-html-plugin](https://github.com/ampedandwired/html-webpack-plugin), you can use [inline-manifest-webpack-plugin](https://github.com/szrenwei/inline-manifest-webpack-plugin) to do this.
222
-
223
-
Using this config the vendor chunk should not be changing its hash unless you change its code or dependencies. Here is a sample output for 2 runs with `moduleB.js` being changed between the runs:
238
+
Using this config the vendor chunk should not be changing its hash, unless you update its code or dependencies. Here is a sample output for 2 runs with `moduleB.js` being changed between the runs:
Notice that **vendor chunk has the same filename**, and **so does the manifest** since we’ve extracted the manifest chunk!
266
+
267
+
## Manifest inlining
268
+
269
+
Inlining the chunk manifest and webpack runtime (to prevent extra HTTP requests), depends on your server setup. There is a nice [walkthrough for Rails-based projects](http://clarkdave.net/2015/01/how-to-use-webpack-with-rails/#including-precompiled-assets-in-views). For server-side rendering in Node.js you can use [webpack-isomorphic-tools](https://github.com/halt-hammerzeit/webpack-isomorphic-tools).
260
270
261
-
Notice that vendor chunk has the same filename!
271
+
T> If your application doesn’t rely on any server-side rendering, it’s often enough to generate a single `index.html` file for your application. To do so, use i.e. [webpack-html-plugin](https://github.com/ampedandwired/html-webpack-plugin) in combination with [script-ext-html-webpack-plugin](https://github.com/numical/script-ext-html-webpack-plugin) or [inline-manifest-webpack-plugin](https://github.com/szrenwei/inline-manifest-webpack-plugin). It will simplify the setup dramatically.
0 commit comments