UNPKG

14.1 kBMarkdownView Raw
1<div align="center">
2 <a href="https://github.com/webpack/webpack">
3 <img width="200" height="200" src="https://webpack.js.org/assets/icon-square-big.svg">
4 </a>
5</div>
6
7[![npm][npm]][npm-url]
8[![node][node]][node-url]
9[![deps][deps]][deps-url]
10[![tests][tests]][tests-url]
11[![coverage][cover]][cover-url]
12[![chat][chat]][chat-url]
13[![size][size]][size-url]
14
15# file-loader
16
17The `file-loader` resolves `import`/`require()` on a file into a url and emits the file into the output directory.
18
19## Getting Started
20
21To begin, you'll need to install `file-loader`:
22
23```console
24$ npm install file-loader --save-dev
25```
26
27Import (or `require`) the target file(s) in one of the bundle's files:
28
29**file.js**
30
31```js
32import img from './file.png';
33```
34
35Then add the loader to your `webpack` config. For example:
36
37**webpack.config.js**
38
39```js
40module.exports = {
41 module: {
42 rules: [
43 {
44 test: /\.(png|jpe?g|gif)$/i,
45 use: [
46 {
47 loader: 'file-loader',
48 },
49 ],
50 },
51 ],
52 },
53};
54```
55
56And run `webpack` via your preferred method. This will emit `file.png` as a file
57in the output directory (with the specified naming convention, if options are
58specified to do so) and returns the public URI of the file.
59
60> ℹ️ By default the filename of the resulting file is the hash of the file's contents with the original extension of the required resource.
61
62## Options
63
64### `name`
65
66Type: `String|Function`
67Default: `'[contenthash].[ext]'`
68
69Specifies a custom filename template for the target file(s) using the query
70parameter `name`. For example, to emit a file from your `context` directory into
71the output directory retaining the full directory structure, you might use:
72
73#### `String`
74
75**webpack.config.js**
76
77```js
78module.exports = {
79 module: {
80 rules: [
81 {
82 test: /\.(png|jpe?g|gif)$/i,
83 loader: 'file-loader',
84 options: {
85 name: '[path][name].[ext]',
86 },
87 },
88 ],
89 },
90};
91```
92
93#### `Function`
94
95**webpack.config.js**
96
97```js
98module.exports = {
99 module: {
100 rules: [
101 {
102 test: /\.(png|jpe?g|gif)$/i,
103 loader: 'file-loader',
104 options: {
105 name(file) {
106 if (process.env.NODE_ENV === 'development') {
107 return '[path][name].[ext]';
108 }
109
110 return '[contenthash].[ext]';
111 },
112 },
113 },
114 ],
115 },
116};
117```
118
119> ℹ️ By default the path and name you specify will output the file in that same directory, and will also use the same URI path to access the file.
120
121### `outputPath`
122
123Type: `String|Function`
124Default: `undefined`
125
126Specify a filesystem path where the target file(s) will be placed.
127
128#### `String`
129
130**webpack.config.js**
131
132```js
133module.exports = {
134 module: {
135 rules: [
136 {
137 test: /\.(png|jpe?g|gif)$/i,
138 loader: 'file-loader',
139 options: {
140 outputPath: 'images',
141 },
142 },
143 ],
144 },
145};
146```
147
148#### `Function`
149
150**webpack.config.js**
151
152```js
153module.exports = {
154 module: {
155 rules: [
156 {
157 test: /\.(png|jpe?g|gif)$/i,
158 loader: 'file-loader',
159 options: {
160 outputPath: (url, resourcePath, context) => {
161 // `resourcePath` is original absolute path to asset
162 // `context` is directory where stored asset (`rootContext`) or `context` option
163
164 // To get relative path you can use
165 // const relativePath = path.relative(context, resourcePath);
166
167 if (/my-custom-image\.png/.test(resourcePath)) {
168 return `other_output_path/${url}`;
169 }
170
171 if (/images/.test(context)) {
172 return `image_output_path/${url}`;
173 }
174
175 return `output_path/${url}`;
176 },
177 },
178 },
179 ],
180 },
181};
182```
183
184### `publicPath`
185
186Type: `String|Function`
187Default: [`__webpack_public_path__`](https://webpack.js.org/api/module-variables/#__webpack_public_path__-webpack-specific-)
188
189Specifies a custom public path for the target file(s).
190
191#### `String`
192
193**webpack.config.js**
194
195```js
196module.exports = {
197 module: {
198 rules: [
199 {
200 test: /\.(png|jpe?g|gif)$/i,
201 loader: 'file-loader',
202 options: {
203 publicPath: 'assets',
204 },
205 },
206 ],
207 },
208};
209```
210
211#### `Function`
212
213**webpack.config.js**
214
215```js
216module.exports = {
217 module: {
218 rules: [
219 {
220 test: /\.(png|jpe?g|gif)$/i,
221 loader: 'file-loader',
222 options: {
223 publicPath: (url, resourcePath, context) => {
224 // `resourcePath` is original absolute path to asset
225 // `context` is directory where stored asset (`rootContext`) or `context` option
226
227 // To get relative path you can use
228 // const relativePath = path.relative(context, resourcePath);
229
230 if (/my-custom-image\.png/.test(resourcePath)) {
231 return `other_public_path/${url}`;
232 }
233
234 if (/images/.test(context)) {
235 return `image_output_path/${url}`;
236 }
237
238 return `public_path/${url}`;
239 },
240 },
241 },
242 ],
243 },
244};
245```
246
247### `postTransformPublicPath`
248
249Type: `Function`
250Default: `undefined`
251
252Specifies a custom function to post-process the generated public path. This can be used to prepend or append dynamic global variables that are only available at runtime, like `__webpack_public_path__`. This would not be possible with just `publicPath`, since it stringifies the values.
253
254**webpack.config.js**
255
256```js
257module.exports = {
258 module: {
259 rules: [
260 {
261 test: /\.(png|jpg|gif)$/i,
262 loader: 'file-loader',
263 options: {
264 publicPath: '/some/path/',
265 postTransformPublicPath: (p) => `__webpack_public_path__ + ${p}`,
266 },
267 },
268 ],
269 },
270};
271```
272
273### `context`
274
275Type: `String`
276Default: [`context`](https://webpack.js.org/configuration/entry-context/#context)
277
278Specifies a custom file context.
279
280```js
281module.exports = {
282 module: {
283 rules: [
284 {
285 test: /\.(png|jpe?g|gif)$/i,
286 use: [
287 {
288 loader: 'file-loader',
289 options: {
290 context: 'project',
291 },
292 },
293 ],
294 },
295 ],
296 },
297};
298```
299
300### `emitFile`
301
302Type: `Boolean`
303Default: `true`
304
305If true, emits a file (writes a file to the filesystem). If false, the loader
306will return a public URI but **will not** emit the file. It is often useful to
307disable this option for server-side packages.
308
309**file.js**
310
311```js
312// bundle file
313import img from './file.png';
314```
315
316**webpack.config.js**
317
318```js
319module.exports = {
320 module: {
321 rules: [
322 {
323 test: /\.css$/i,
324 use: [
325 {
326 loader: 'file-loader',
327 options: {
328 emitFile: false,
329 },
330 },
331 ],
332 },
333 ],
334 },
335};
336```
337
338### `regExp`
339
340Type: `RegExp`
341Default: `undefined`
342
343Specifies a Regular Expression to one or many parts of the target file path.
344The capture groups can be reused in the `name` property using `[N]`
345[placeholder](https://github.com/webpack-contrib/file-loader#placeholders).
346
347**file.js**
348
349```js
350import img from './customer01/file.png';
351```
352
353**webpack.config.js**
354
355```js
356module.exports = {
357 module: {
358 rules: [
359 {
360 test: /\.(png|jpe?g|gif)$/i,
361 use: [
362 {
363 loader: 'file-loader',
364 options: {
365 regExp: /\/([a-z0-9]+)\/[a-z0-9]+\.png$/i,
366 name: '[1]-[name].[ext]',
367 },
368 },
369 ],
370 },
371 ],
372 },
373};
374```
375
376> ℹ️ If `[0]` is used, it will be replaced by the entire tested string, whereas `[1]` will contain the first capturing parenthesis of your regex and so on...
377
378## Placeholders
379
380Full information about placeholders you can find [here](https://github.com/webpack/loader-utils#interpolatename).
381
382### `[ext]`
383
384Type: `String`
385Default: `file.extname`
386
387The file extension of the target file/resource.
388
389### `[name]`
390
391Type: `String`
392Default: `file.basename`
393
394The basename of the file/resource.
395
396### `[path]`
397
398Type: `String`
399Default: `file.directory`
400
401The path of the resource relative to the webpack/config `context`.
402
403### `[folder]`
404
405Type: `String`
406Default: `file.folder`
407
408The folder of the resource is in.
409
410### `[emoji]`
411
412Type: `String`
413Default: `undefined`
414
415A random emoji representation of `content`.
416
417### `[emoji:<length>]`
418
419Type: `String`
420Default: `undefined`
421
422Same as above, but with a customizable number of emojis
423
424### `[hash]`
425
426Type: `String`
427Default: `md5`
428
429Specifies the hash method to use for hashing the file content.
430
431### `[contenthash]`
432
433Type: `String`
434Default: `md5`
435
436Specifies the hash method to use for hashing the file content.
437
438### `[<hashType>:hash:<digestType>:<length>]`
439
440Type: `String`
441
442The hash of options.content (Buffer) (by default it's the hex digest of the hash).
443
444#### `digestType`
445
446Type: `String`
447Default: `'hex'`
448
449The [digest](https://en.wikipedia.org/wiki/Cryptographic_hash_function) that the
450hash function should use. Valid values include: base26, base32, base36,
451base49, base52, base58, base62, base64, and hex.
452
453#### `hashType`
454
455Type: `String`
456Default: `'md5'`
457
458The type of hash that the has function should use. Valid values include: `md5`,
459`sha1`, `sha256`, and `sha512`.
460
461#### `length`
462
463Type: `Number`
464Default: `undefined`
465
466Users may also specify a length for the computed hash.
467
468### `[N]`
469
470Type: `String`
471Default: `undefined`
472
473The n-th match obtained from matching the current file name against the `regExp`.
474
475## Examples
476
477### Names
478
479The following examples show how one might use `file-loader` and what the result would be.
480
481**file.js**
482
483```js
484import png from './image.png';
485```
486
487**webpack.config.js**
488
489```js
490module.exports = {
491 module: {
492 rules: [
493 {
494 test: /\.(png|jpe?g|gif)$/i,
495 use: [
496 {
497 loader: 'file-loader',
498 options: {
499 name: 'dirname/[contenthash].[ext]',
500 },
501 },
502 ],
503 },
504 ],
505 },
506};
507```
508
509Result:
510
511```bash
512# result
513dirname/0dcbbaa701328ae351f.png
514```
515
516---
517
518**file.js**
519
520```js
521import png from './image.png';
522```
523
524**webpack.config.js**
525
526```js
527module.exports = {
528 module: {
529 rules: [
530 {
531 test: /\.(png|jpe?g|gif)$/i,
532 use: [
533 {
534 loader: 'file-loader',
535 options: {
536 name: '[sha512:hash:base64:7].[ext]',
537 },
538 },
539 ],
540 },
541 ],
542 },
543};
544```
545
546Result:
547
548```bash
549# result
550gdyb21L.png
551```
552
553---
554
555**file.js**
556
557```js
558import png from './path/to/file.png';
559```
560
561**webpack.config.js**
562
563```js
564module.exports = {
565 module: {
566 rules: [
567 {
568 test: /\.(png|jpe?g|gif)$/i,
569 use: [
570 {
571 loader: 'file-loader',
572 options: {
573 name: '[path][name].[ext]?[contenthash]',
574 },
575 },
576 ],
577 },
578 ],
579 },
580};
581```
582
583Result:
584
585```bash
586# result
587path/to/file.png?e43b20c069c4a01867c31e98cbce33c9
588```
589
590### Dynamic public path depending on environment variable at run time
591
592An application might want to configure different CDN hosts depending on an environment variable that is only available when running the application. This can be an advantage, as only one build of the application is necessary, which behaves differntly depending on environment variables of the deployment environment. Since file-loader is applied when compiling the application, and not when running it, the environment variable cannot be used in the file-loader configuration. A way around this is setting the `__webpack_public_path__` to the desired CDN host depending on the environment variable at the entrypoint of the application. The option `postTransformPublicPath` can be used to configure a custom path depending on a variable like `__webpack_public_path__`.
593
594**main.js**
595
596```js
597const namespace = process.env.NAMESPACE;
598const assetPrefixForNamespace = (namespace) => {
599 switch (namespace) {
600 case 'prod':
601 return 'https://cache.myserver.net/web';
602 case 'uat':
603 return 'https://cache-uat.myserver.net/web';
604 case 'st':
605 return 'https://cache-st.myserver.net/web';
606 case 'dev':
607 return 'https://cache-dev.myserver.net/web';
608 default:
609 return '';
610 }
611};
612__webpack_public_path__ = `${assetPrefixForNamespace(namespace)}/`;
613```
614
615**file.js**
616
617```js
618import png from './image.png';
619```
620
621**webpack.config.js**
622
623```js
624module.exports = {
625 module: {
626 rules: [
627 {
628 test: /\.(png|jpg|gif)$/i,
629 loader: 'file-loader',
630 options: {
631 name: '[name].[contenthash].[ext]',
632 outputPath: 'static/assets/',
633 publicPath: 'static/assets/',
634 postTransformPublicPath: (p) => `__webpack_public_path__ + ${p}`,
635 },
636 },
637 ],
638 },
639};
640```
641
642Result when run with `NAMESPACE=prod` env variable:
643
644```bash
645# result
646https://cache.myserver.net/web/static/assets/image.somehash.png
647```
648
649Result when run with `NAMESPACE=dev` env variable:
650
651```bash
652# result
653https://cache-dev.myserver.net/web/static/assets/image.somehash.png
654```
655
656## Contributing
657
658Please take a moment to read our contributing guidelines if you haven't yet done so.
659
660[CONTRIBUTING](./.github/CONTRIBUTING.md)
661
662## License
663
664[MIT](./LICENSE)
665
666[npm]: https://img.shields.io/npm/v/file-loader.svg
667[npm-url]: https://npmjs.com/package/file-loader
668[node]: https://img.shields.io/node/v/file-loader.svg
669[node-url]: https://nodejs.org
670[deps]: https://david-dm.org/webpack-contrib/file-loader.svg
671[deps-url]: https://david-dm.org/webpack-contrib/file-loader
672[tests]: https://dev.azure.com/webpack-contrib/file-loader/_apis/build/status/webpack-contrib.file-loader?branchName=master
673[tests-url]: https://dev.azure.com/webpack-contrib/file-loader/_build/latest?definitionId=2&branchName=master
674[cover]: https://codecov.io/gh/webpack-contrib/file-loader/branch/master/graph/badge.svg
675[cover-url]: https://codecov.io/gh/webpack-contrib/file-loader
676[chat]: https://img.shields.io/badge/gitter-webpack%2Fwebpack-brightgreen.svg
677[chat-url]: https://gitter.im/webpack/webpack
678[size]: https://packagephobia.now.sh/badge?p=file-loader
679[size-url]: https://packagephobia.now.sh/result?p=file-loader