You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

255 lines
9.2 KiB

4 years ago
  1. # loader-utils
  2. ## Methods
  3. ### `getOptions`
  4. Recommended way to retrieve the options of a loader invocation:
  5. ```javascript
  6. // inside your loader
  7. const options = loaderUtils.getOptions(this);
  8. ```
  9. 1. If `this.query` is a string:
  10. - Tries to parse the query string and returns a new object
  11. - Throws if it's not a valid query string
  12. 2. If `this.query` is object-like, it just returns `this.query`
  13. 3. In any other case, it just returns `null`
  14. **Please note:** The returned `options` object is *read-only*. It may be re-used across multiple invocations.
  15. If you pass it on to another library, make sure to make a *deep copy* of it:
  16. ```javascript
  17. const options = Object.assign(
  18. {},
  19. defaultOptions,
  20. loaderUtils.getOptions(this) // it is safe to pass null to Object.assign()
  21. );
  22. // don't forget nested objects or arrays
  23. options.obj = Object.assign({}, options.obj);
  24. options.arr = options.arr.slice();
  25. someLibrary(options);
  26. ```
  27. [clone](https://www.npmjs.com/package/clone) is a good library to make a deep copy of the options.
  28. #### Options as query strings
  29. If the loader options have been passed as loader query string (`loader?some&params`), the string is parsed by using [`parseQuery`](#parsequery).
  30. ### `parseQuery`
  31. Parses a passed string (e.g. `loaderContext.resourceQuery`) as a query string, and returns an object.
  32. ``` javascript
  33. const params = loaderUtils.parseQuery(this.resourceQuery); // resource: `file?param1=foo`
  34. if (params.param1 === "foo") {
  35. // do something
  36. }
  37. ```
  38. The string is parsed like this:
  39. ``` text
  40. -> Error
  41. ? -> {}
  42. ?flag -> { flag: true }
  43. ?+flag -> { flag: true }
  44. ?-flag -> { flag: false }
  45. ?xyz=test -> { xyz: "test" }
  46. ?xyz=1 -> { xyz: "1" } // numbers are NOT parsed
  47. ?xyz[]=a -> { xyz: ["a"] }
  48. ?flag1&flag2 -> { flag1: true, flag2: true }
  49. ?+flag1,-flag2 -> { flag1: true, flag2: false }
  50. ?xyz[]=a,xyz[]=b -> { xyz: ["a", "b"] }
  51. ?a%2C%26b=c%2C%26d -> { "a,&b": "c,&d" }
  52. ?{data:{a:1},isJSON5:true} -> { data: { a: 1 }, isJSON5: true }
  53. ```
  54. ### `stringifyRequest`
  55. Turns a request into a string that can be used inside `require()` or `import` while avoiding absolute paths.
  56. Use it instead of `JSON.stringify(...)` if you're generating code inside a loader.
  57. **Why is this necessary?** Since webpack calculates the hash before module paths are translated into module ids, we must avoid absolute paths to ensure
  58. consistent hashes across different compilations.
  59. This function:
  60. - resolves absolute requests into relative requests if the request and the module are on the same hard drive
  61. - replaces `\` with `/` if the request and the module are on the same hard drive
  62. - won't change the path at all if the request and the module are on different hard drives
  63. - applies `JSON.stringify` to the result
  64. ```javascript
  65. loaderUtils.stringifyRequest(this, "./test.js");
  66. // "\"./test.js\""
  67. loaderUtils.stringifyRequest(this, ".\\test.js");
  68. // "\"./test.js\""
  69. loaderUtils.stringifyRequest(this, "test");
  70. // "\"test\""
  71. loaderUtils.stringifyRequest(this, "test/lib/index.js");
  72. // "\"test/lib/index.js\""
  73. loaderUtils.stringifyRequest(this, "otherLoader?andConfig!test?someConfig");
  74. // "\"otherLoader?andConfig!test?someConfig\""
  75. loaderUtils.stringifyRequest(this, require.resolve("test"));
  76. // "\"../node_modules/some-loader/lib/test.js\""
  77. loaderUtils.stringifyRequest(this, "C:\\module\\test.js");
  78. // "\"../../test.js\"" (on Windows, in case the module and the request are on the same drive)
  79. loaderUtils.stringifyRequest(this, "C:\\module\\test.js");
  80. // "\"C:\\module\\test.js\"" (on Windows, in case the module and the request are on different drives)
  81. loaderUtils.stringifyRequest(this, "\\\\network-drive\\test.js");
  82. // "\"\\\\network-drive\\\\test.js\"" (on Windows, in case the module and the request are on different drives)
  83. ```
  84. ### `urlToRequest`
  85. Converts some resource URL to a webpack module request.
  86. > i Before call `urlToRequest` you need call `isUrlRequest` to ensure it is requestable url
  87. ```javascript
  88. const url = "path/to/module.js";
  89. if (loaderUtils.isUrlRequest(url)) {
  90. // Logic for requestable url
  91. const request = loaderUtils.urlToRequest(url);
  92. } else {
  93. // Logic for not requestable url
  94. }
  95. ```
  96. Simple example:
  97. ```javascript
  98. const url = "path/to/module.js";
  99. const request = loaderUtils.urlToRequest(url); // "./path/to/module.js"
  100. ```
  101. #### Module URLs
  102. Any URL containing a `~` will be interpreted as a module request. Anything after the `~` will be considered the request path.
  103. ```javascript
  104. const url = "~path/to/module.js";
  105. const request = loaderUtils.urlToRequest(url); // "path/to/module.js"
  106. ```
  107. #### Root-relative URLs
  108. URLs that are root-relative (start with `/`) can be resolved relative to some arbitrary path by using the `root` parameter:
  109. ```javascript
  110. const url = "/path/to/module.js";
  111. const root = "./root";
  112. const request = loaderUtils.urlToRequest(url, root); // "./root/path/to/module.js"
  113. ```
  114. To convert a root-relative URL into a module URL, specify a `root` value that starts with `~`:
  115. ```javascript
  116. const url = "/path/to/module.js";
  117. const root = "~";
  118. const request = loaderUtils.urlToRequest(url, root); // "path/to/module.js"
  119. ```
  120. ### `interpolateName`
  121. Interpolates a filename template using multiple placeholders and/or a regular expression.
  122. The template and regular expression are set as query params called `name` and `regExp` on the current loader's context.
  123. ```javascript
  124. const interpolatedName = loaderUtils.interpolateName(loaderContext, name, options);
  125. ```
  126. The following tokens are replaced in the `name` parameter:
  127. * `[ext]` the extension of the resource
  128. * `[name]` the basename of the resource
  129. * `[path]` the path of the resource relative to the `context` query parameter or option.
  130. * `[folder]` the folder of the resource is in.
  131. * `[emoji]` a random emoji representation of `options.content`
  132. * `[emoji:<length>]` same as above, but with a customizable number of emojis
  133. * `[contenthash]` the hash of `options.content` (Buffer) (by default it's the hex digest of the md5 hash)
  134. * `[<hashType>:contenthash:<digestType>:<length>]` optionally one can configure
  135. * other `hashType`s, i. e. `sha1`, `md5`, `sha256`, `sha512`
  136. * other `digestType`s, i. e. `hex`, `base26`, `base32`, `base36`, `base49`, `base52`, `base58`, `base62`, `base64`
  137. * and `length` the length in chars
  138. * `[hash]` the hash of `options.content` (Buffer) (by default it's the hex digest of the md5 hash)
  139. * `[<hashType>:hash:<digestType>:<length>]` optionally one can configure
  140. * other `hashType`s, i. e. `sha1`, `md5`, `sha256`, `sha512`
  141. * other `digestType`s, i. e. `hex`, `base26`, `base32`, `base36`, `base49`, `base52`, `base58`, `base62`, `base64`
  142. * and `length` the length in chars
  143. * `[N]` the N-th match obtained from matching the current file name against `options.regExp`
  144. In loader context `[hash]` and `[contenthash]` are the same, but we recommend using `[contenthash]` for avoid misleading.
  145. Examples
  146. ``` javascript
  147. // loaderContext.resourcePath = "/app/js/javascript.js"
  148. loaderUtils.interpolateName(loaderContext, "js/[hash].script.[ext]", { content: ... });
  149. // => js/9473fdd0d880a43c21b7778d34872157.script.js
  150. // loaderContext.resourcePath = "/app/js/javascript.js"
  151. loaderUtils.interpolateName(loaderContext, "js/[contenthash].script.[ext]", { content: ... });
  152. // => js/9473fdd0d880a43c21b7778d34872157.script.js
  153. // loaderContext.resourcePath = "/app/page.html"
  154. loaderUtils.interpolateName(loaderContext, "html-[hash:6].html", { content: ... });
  155. // => html-9473fd.html
  156. // loaderContext.resourcePath = "/app/flash.txt"
  157. loaderUtils.interpolateName(loaderContext, "[hash]", { content: ... });
  158. // => c31e9820c001c9c4a86bce33ce43b679
  159. // loaderContext.resourcePath = "/app/img/image.gif"
  160. loaderUtils.interpolateName(loaderContext, "[emoji]", { content: ... });
  161. // => 👍
  162. // loaderContext.resourcePath = "/app/img/image.gif"
  163. loaderUtils.interpolateName(loaderContext, "[emoji:4]", { content: ... });
  164. // => 🙍🏢📤🐝
  165. // loaderContext.resourcePath = "/app/img/image.png"
  166. loaderUtils.interpolateName(loaderContext, "[sha512:hash:base64:7].[ext]", { content: ... });
  167. // => 2BKDTjl.png
  168. // use sha512 hash instead of md5 and with only 7 chars of base64
  169. // loaderContext.resourcePath = "/app/img/myself.png"
  170. // loaderContext.query.name =
  171. loaderUtils.interpolateName(loaderContext, "picture.png");
  172. // => picture.png
  173. // loaderContext.resourcePath = "/app/dir/file.png"
  174. loaderUtils.interpolateName(loaderContext, "[path][name].[ext]?[hash]", { content: ... });
  175. // => /app/dir/file.png?9473fdd0d880a43c21b7778d34872157
  176. // loaderContext.resourcePath = "/app/js/page-home.js"
  177. loaderUtils.interpolateName(loaderContext, "script-[1].[ext]", { regExp: "page-(.*)\\.js", content: ... });
  178. // => script-home.js
  179. ```
  180. ### `getHashDigest`
  181. ``` javascript
  182. const digestString = loaderUtils.getHashDigest(buffer, hashType, digestType, maxLength);
  183. ```
  184. * `buffer` the content that should be hashed
  185. * `hashType` one of `sha1`, `md5`, `sha256`, `sha512` or any other node.js supported hash type
  186. * `digestType` one of `hex`, `base26`, `base32`, `base36`, `base49`, `base52`, `base58`, `base62`, `base64`
  187. * `maxLength` the maximum length in chars
  188. ## License
  189. MIT (http://www.opensource.org/licenses/mit-license.php)