7b56fd0344feea05895f0cbaf75e03d3111c17c73991bf641896a1c9c358d8bfa169df7e22729c8002265439c0eb4fd90f7a8ff17908a05c2d3a6bfdca7c5f 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. <div align="center">
  2. <a href="https://webpack.js.org/">
  3. <img width="200" height="200" src="https://cdn.rawgit.com/webpack/media/e7485eb2/logo/icon-square-big.svg">
  4. </a>
  5. </div>
  6. [![npm][npm]][npm-url]
  7. [![node][node]][node-url]
  8. [![deps][deps]][deps-url]
  9. [![tests][tests]][tests-url]
  10. [![coverage][cover]][cover-url]
  11. [![chat][chat]][chat-url]
  12. [![size][size]][size-url]
  13. # cache-loader
  14. The `cache-loader` allow to Caches the result of following loaders on disk (default) or in the database.
  15. ## Getting Started
  16. To begin, you'll need to install `cache-loader`:
  17. ```console
  18. npm install --save-dev cache-loader
  19. ```
  20. Add this loader in front of other (expensive) loaders to cache the result on disk.
  21. **webpack.config.js**
  22. ```js
  23. module.exports = {
  24. module: {
  25. rules: [
  26. {
  27. test: /\.ext$/,
  28. use: ['cache-loader', ...loaders],
  29. include: path.resolve('src'),
  30. },
  31. ],
  32. },
  33. };
  34. ```
  35. > ⚠️ Note that there is an overhead for saving the reading and saving the cache file, so only use this loader to cache expensive loaders.
  36. ## Options
  37. | Name | Type | n Default | Description |
  38. | :-------------------: | :----------------------------------------------: | :-----------------------------------------------------: | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  39. | **`cacheContext`** | `{String}` | `undefined` | Allows you to override the default cache context in order to generate the cache relatively to a path. By default it will use absolute paths |
  40. | **`cacheKey`** | `{Function(options, request) -> {String}}` | `undefined` | Allows you to override default cache key generator |
  41. | **`cacheDirectory`** | `{String}` | `findCacheDir({ name: 'cache-loader' }) or os.tmpdir()` | Provide a cache directory where cache items should be stored (used for default read/write implementation) |
  42. | **`cacheIdentifier`** | `{String}` | `cache-loader:{version} {process.env.NODE_ENV}` | Provide an invalidation identifier which is used to generate the hashes. You can use it for extra dependencies of loaders (used for default read/write implementation) |
  43. | **`compare`** | `{Function(stats, dep) -> {Boolean}}` | `undefined` | Allows you to override default comparison function between the cached dependency and the one is being read. Return `true` to use the cached resource |
  44. | **`precision`** | `{Number}` | `0` | Round `mtime` by this number of milliseconds both for `stats` and `dep` before passing those params to the comparing function |
  45. | **`read`** | `{Function(cacheKey, callback) -> {void}}` | `undefined` | Allows you to override default read cache data from file |
  46. | **`readOnly`** | `{Boolean}` | `false` | Allows you to override default value and make the cache read only (useful for some environments where you don't want the cache to be updated, only read from it) |
  47. | **`write`** | `{Function(cacheKey, data, callback) -> {void}}` | `undefined` | Allows you to override default write cache data to file (e.g. Redis, memcached) |
  48. ## Examples
  49. ### Basic
  50. **webpack.config.js**
  51. ```js
  52. module.exports = {
  53. module: {
  54. rules: [
  55. {
  56. test: /\.js$/,
  57. use: ['cache-loader', 'babel-loader'],
  58. include: path.resolve('src'),
  59. },
  60. ],
  61. },
  62. };
  63. ```
  64. ### Database Integration
  65. **webpack.config.js**
  66. ```js
  67. // Or different database client - memcached, mongodb, ...
  68. const redis = require('redis');
  69. const crypto = require('crypto');
  70. // ...
  71. // connect to client
  72. // ...
  73. const BUILD_CACHE_TIMEOUT = 24 * 3600; // 1 day
  74. function digest(str) {
  75. return crypto
  76. .createHash('md5')
  77. .update(str)
  78. .digest('hex');
  79. }
  80. // Generate own cache key
  81. function cacheKey(options, request) {
  82. return `build:cache:${digest(request)}`;
  83. }
  84. // Read data from database and parse them
  85. function read(key, callback) {
  86. client.get(key, (err, result) => {
  87. if (err) {
  88. return callback(err);
  89. }
  90. if (!result) {
  91. return callback(new Error(`Key ${key} not found`));
  92. }
  93. try {
  94. let data = JSON.parse(result);
  95. callback(null, data);
  96. } catch (e) {
  97. callback(e);
  98. }
  99. });
  100. }
  101. // Write data to database under cacheKey
  102. function write(key, data, callback) {
  103. client.set(key, JSON.stringify(data), 'EX', BUILD_CACHE_TIMEOUT, callback);
  104. }
  105. module.exports = {
  106. module: {
  107. rules: [
  108. {
  109. test: /\.js$/,
  110. use: [
  111. {
  112. loader: 'cache-loader',
  113. options: {
  114. cacheKey,
  115. read,
  116. write,
  117. },
  118. },
  119. 'babel-loader',
  120. ],
  121. include: path.resolve('src'),
  122. },
  123. ],
  124. },
  125. };
  126. ```
  127. ## Contributing
  128. Please take a moment to read our contributing guidelines if you haven't yet done so.
  129. [CONTRIBUTING](./.github/CONTRIBUTING.md)
  130. ## License
  131. [MIT](./LICENSE)
  132. [npm]: https://img.shields.io/npm/v/cache-loader.svg
  133. [npm-url]: https://npmjs.com/package/cache-loader
  134. [node]: https://img.shields.io/node/v/cache-loader.svg
  135. [node-url]: https://nodejs.org
  136. [deps]: https://david-dm.org/webpack-contrib/cache-loader.svg
  137. [deps-url]: https://david-dm.org/webpack-contrib/cache-loader
  138. [tests]: https://dev.azure.com/webpack-contrib/cache-loader/_apis/build/status/webpack-contrib.cache-loader?branchName=master
  139. [tests-url]: https://dev.azure.com/webpack-contrib/cache-loader/_build/latest?definitionId=4&branchName=master
  140. [cover]: https://codecov.io/gh/webpack-contrib/cache-loader/branch/master/graph/badge.svg
  141. [cover-url]: https://codecov.io/gh/webpack-contrib/cache-loader
  142. [chat]: https://badges.gitter.im/webpack/webpack.svg
  143. [chat-url]: https://gitter.im/webpack/webpack
  144. [size]: https://packagephobia.now.sh/badge?p=cache-loader
  145. [size-url]: https://packagephobia.now.sh/result?p=cache-loader