Projekt

Obecné

Profil

Stáhnout (10.1 KB) Statistiky
| Větev: | Revize:
1 3a515b92 cagy
# loader-utils
2
3
## Methods
4
5
### `getOptions`
6
7
Recommended way to retrieve the options of a loader invocation:
8
9
```javascript
10
// inside your loader
11
const options = loaderUtils.getOptions(this);
12
```
13
14
1. 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
17
2. If `this.query` is object-like, it just returns `this.query`
18
3. 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.
21
If you pass it on to another library, make sure to make a *deep copy* of it:
22
23
```javascript
24
const 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
30
options.obj = Object.assign({}, options.obj); 
31
options.arr = options.arr.slice();
32
someLibrary(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
39
If the loader options have been passed as loader query string (`loader?some&params`), the string is parsed by using [`parseQuery`](#parsequery).
40
41
### `parseQuery`
42
43
Parses a passed string (e.g. `loaderContext.resourceQuery`) as a query string, and returns an object.
44
45
``` javascript
46
const params = loaderUtils.parseQuery(this.resourceQuery); // resource: `file?param1=foo`
47
if (params.param1 === "foo") {
48
	// do something
49
}
50
```
51
52
The 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
72
Turns a request into a string that can be used inside `require()` or `import` while avoiding absolute paths.
73
Use 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
76
consistent hashes across different compilations.
77
78
This 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
86
loaderUtils.stringifyRequest(this, "./test.js");
87
// "\"./test.js\""
88
89
loaderUtils.stringifyRequest(this, ".\\test.js");
90
// "\"./test.js\""
91
92
loaderUtils.stringifyRequest(this, "test");
93
// "\"test\""
94
95
loaderUtils.stringifyRequest(this, "test/lib/index.js");
96
// "\"test/lib/index.js\""
97
98
loaderUtils.stringifyRequest(this, "otherLoader?andConfig!test?someConfig");
99
// "\"otherLoader?andConfig!test?someConfig\""
100
101
loaderUtils.stringifyRequest(this, require.resolve("test"));
102
// "\"../node_modules/some-loader/lib/test.js\""
103
104
loaderUtils.stringifyRequest(this, "C:\\module\\test.js");
105
// "\"../../test.js\"" (on Windows, in case the module and the request are on the same drive)
106
107
loaderUtils.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
110
loaderUtils.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
116
Converts 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
121
const url = "path/to/module.js";
122
123
if (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
131
Simple example:
132
133
```javascript
134
const url = "path/to/module.js";
135
const request = loaderUtils.urlToRequest(url); // "./path/to/module.js"
136
```
137
138
#### Module URLs
139
140
Any URL containing a `~` will be interpreted as a module request. Anything after the `~` will be considered the request path.
141
142
```javascript
143
const url = "~path/to/module.js";
144
const request = loaderUtils.urlToRequest(url); // "path/to/module.js"
145
```
146
147
#### Root-relative URLs
148
149
URLs that are root-relative (start with `/`) can be resolved relative to some arbitrary path by using the `root` parameter:
150
151
```javascript
152
const url = "/path/to/module.js";
153
const root = "./root";
154
const request = loaderUtils.urlToRequest(url, root); // "./root/path/to/module.js"
155
```
156
157
To convert a root-relative URL into a module URL, specify a `root` value that starts with `~`:
158
159
```javascript
160
const url = "/path/to/module.js";
161
const root = "~";
162
const request = loaderUtils.urlToRequest(url, root); // "path/to/module.js"
163
```
164
165
### `interpolateName`
166
167
Interpolates a filename template using multiple placeholders and/or a regular expression.
168
The template and regular expression are set as query params called `name` and `regExp` on the current loader's context.
169
170
```javascript
171
const interpolatedName = loaderUtils.interpolateName(loaderContext, name, options);
172
```
173
174
The 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
195
In loader context `[hash]` and `[contenthash]` are the same, but we recommend using `[contenthash]` for avoid misleading.
196
197
Examples
198
199
``` javascript
200
// loaderContext.resourcePath = "/absolute/path/to/app/js/javascript.js"
201
loaderUtils.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"
206
loaderUtils.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"
210
loaderUtils.interpolateName(loaderContext, "js/[contenthash].script.[ext]", { content: ... });
211
// => js/9473fdd0d880a43c21b7778d34872157.script.js
212
213
// loaderContext.resourcePath = "/absolute/path/to/app/page.html"
214
loaderUtils.interpolateName(loaderContext, "html-[hash:6].html", { content: ... });
215
// => html-9473fd.html
216
217
// loaderContext.resourcePath = "/absolute/path/to/app/flash.txt"
218
loaderUtils.interpolateName(loaderContext, "[hash]", { content: ... });
219
// => c31e9820c001c9c4a86bce33ce43b679
220
221
// loaderContext.resourcePath = "/absolute/path/to/app/img/image.gif"
222
loaderUtils.interpolateName(loaderContext, "[emoji]", { content: ... });
223
// => 👍
224
225
// loaderContext.resourcePath = "/absolute/path/to/app/img/image.gif"
226
loaderUtils.interpolateName(loaderContext, "[emoji:4]", { content: ... });
227
// => 🙍🏢📤🐝
228
229
// loaderContext.resourcePath = "/absolute/path/to/app/img/image.png"
230
loaderUtils.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 =
236
loaderUtils.interpolateName(loaderContext, "picture.png");
237
// => picture.png
238
239
// loaderContext.resourcePath = "/absolute/path/to/app/dir/file.png"
240
loaderUtils.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"
244
loaderUtils.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"
249
loaderUtils.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
265
const 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
275
MIT (http://www.opensource.org/licenses/mit-license.php)