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