UNPKG

15.7 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(resourcePath, resourceQuery) {
106 // `resourcePath` - `/absolute/path/to/file.js`
107 // `resourceQuery` - `?foo=bar`
108
109 if (process.env.NODE_ENV === 'development') {
110 return '[path][name].[ext]';
111 }
112
113 return '[contenthash].[ext]';
114 },
115 },
116 },
117 ],
118 },
119};
120```
121
122> ℹ️ 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.
123
124### `outputPath`
125
126Type: `String|Function`
127Default: `undefined`
128
129Specify a filesystem path where the target file(s) will be placed.
130
131#### `String`
132
133**webpack.config.js**
134
135```js
136module.exports = {
137 module: {
138 rules: [
139 {
140 test: /\.(png|jpe?g|gif)$/i,
141 loader: 'file-loader',
142 options: {
143 outputPath: 'images',
144 },
145 },
146 ],
147 },
148};
149```
150
151#### `Function`
152
153**webpack.config.js**
154
155```js
156module.exports = {
157 module: {
158 rules: [
159 {
160 test: /\.(png|jpe?g|gif)$/i,
161 loader: 'file-loader',
162 options: {
163 outputPath: (url, resourcePath, context) => {
164 // `resourcePath` is original absolute path to asset
165 // `context` is directory where stored asset (`rootContext`) or `context` option
166
167 // To get relative path you can use
168 // const relativePath = path.relative(context, resourcePath);
169
170 if (/my-custom-image\.png/.test(resourcePath)) {
171 return `other_output_path/${url}`;
172 }
173
174 if (/images/.test(context)) {
175 return `image_output_path/${url}`;
176 }
177
178 return `output_path/${url}`;
179 },
180 },
181 },
182 ],
183 },
184};
185```
186
187### `publicPath`
188
189Type: `String|Function`
190Default: [`__webpack_public_path__`](https://webpack.js.org/api/module-variables/#__webpack_public_path__-webpack-specific-)
191
192Specifies a custom public path for the target file(s).
193
194#### `String`
195
196**webpack.config.js**
197
198```js
199module.exports = {
200 module: {
201 rules: [
202 {
203 test: /\.(png|jpe?g|gif)$/i,
204 loader: 'file-loader',
205 options: {
206 publicPath: 'assets',
207 },
208 },
209 ],
210 },
211};
212```
213
214#### `Function`
215
216**webpack.config.js**
217
218```js
219module.exports = {
220 module: {
221 rules: [
222 {
223 test: /\.(png|jpe?g|gif)$/i,
224 loader: 'file-loader',
225 options: {
226 publicPath: (url, resourcePath, context) => {
227 // `resourcePath` is original absolute path to asset
228 // `context` is directory where stored asset (`rootContext`) or `context` option
229
230 // To get relative path you can use
231 // const relativePath = path.relative(context, resourcePath);
232
233 if (/my-custom-image\.png/.test(resourcePath)) {
234 return `other_public_path/${url}`;
235 }
236
237 if (/images/.test(context)) {
238 return `image_output_path/${url}`;
239 }
240
241 return `public_path/${url}`;
242 },
243 },
244 },
245 ],
246 },
247};
248```
249
250### `postTransformPublicPath`
251
252Type: `Function`
253Default: `undefined`
254
255Specifies 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.
256
257**webpack.config.js**
258
259```js
260module.exports = {
261 module: {
262 rules: [
263 {
264 test: /\.(png|jpg|gif)$/i,
265 loader: 'file-loader',
266 options: {
267 publicPath: '/some/path/',
268 postTransformPublicPath: (p) => `__webpack_public_path__ + ${p}`,
269 },
270 },
271 ],
272 },
273};
274```
275
276### `context`
277
278Type: `String`
279Default: [`context`](https://webpack.js.org/configuration/entry-context/#context)
280
281Specifies a custom file context.
282
283```js
284module.exports = {
285 module: {
286 rules: [
287 {
288 test: /\.(png|jpe?g|gif)$/i,
289 use: [
290 {
291 loader: 'file-loader',
292 options: {
293 context: 'project',
294 },
295 },
296 ],
297 },
298 ],
299 },
300};
301```
302
303### `emitFile`
304
305Type: `Boolean`
306Default: `true`
307
308If true, emits a file (writes a file to the filesystem). If false, the loader
309will return a public URI but **will not** emit the file. It is often useful to
310disable this option for server-side packages.
311
312**file.js**
313
314```js
315// bundle file
316import img from './file.png';
317```
318
319**webpack.config.js**
320
321```js
322module.exports = {
323 module: {
324 rules: [
325 {
326 test: /\.css$/i,
327 use: [
328 {
329 loader: 'file-loader',
330 options: {
331 emitFile: false,
332 },
333 },
334 ],
335 },
336 ],
337 },
338};
339```
340
341### `regExp`
342
343Type: `RegExp`
344Default: `undefined`
345
346Specifies a Regular Expression to one or many parts of the target file path.
347The capture groups can be reused in the `name` property using `[N]`
348[placeholder](https://github.com/webpack-contrib/file-loader#placeholders).
349
350**file.js**
351
352```js
353import img from './customer01/file.png';
354```
355
356**webpack.config.js**
357
358```js
359module.exports = {
360 module: {
361 rules: [
362 {
363 test: /\.(png|jpe?g|gif)$/i,
364 use: [
365 {
366 loader: 'file-loader',
367 options: {
368 regExp: /\/([a-z0-9]+)\/[a-z0-9]+\.png$/i,
369 name: '[1]-[name].[ext]',
370 },
371 },
372 ],
373 },
374 ],
375 },
376};
377```
378
379> ℹ️ 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...
380
381### `esModule`
382
383Type: `Boolean`
384Default: `true`
385
386By default, `file-loader` generates JS modules that use the ES modules syntax.
387There are some cases in which using ES modules is beneficial, like in the case of [module concatenation](https://webpack.js.org/plugins/module-concatenation-plugin/) and [tree shaking](https://webpack.js.org/guides/tree-shaking/).
388
389You can enable a CommonJS module syntax using:
390
391**webpack.config.js**
392
393```js
394module.exports = {
395 module: {
396 rules: [
397 {
398 test: /\.css$/,
399 use: [
400 {
401 loader: 'file-loader',
402 options: {
403 esModule: false,
404 },
405 },
406 ],
407 },
408 ],
409 },
410};
411```
412
413## Placeholders
414
415Full information about placeholders you can find [here](https://github.com/webpack/loader-utils#interpolatename).
416
417### `[ext]`
418
419Type: `String`
420Default: `file.extname`
421
422The file extension of the target file/resource.
423
424### `[name]`
425
426Type: `String`
427Default: `file.basename`
428
429The basename of the file/resource.
430
431### `[path]`
432
433Type: `String`
434Default: `file.directory`
435
436The path of the resource relative to the webpack/config `context`.
437
438### `[folder]`
439
440Type: `String`
441Default: `file.folder`
442
443The folder of the resource is in.
444
445### `[query]`
446
447Type: `String`
448Default: `file.query`
449
450The query of the resource, i.e. `?foo=bar`.
451
452### `[emoji]`
453
454Type: `String`
455Default: `undefined`
456
457A random emoji representation of `content`.
458
459### `[emoji:<length>]`
460
461Type: `String`
462Default: `undefined`
463
464Same as above, but with a customizable number of emojis
465
466### `[hash]`
467
468Type: `String`
469Default: `md5`
470
471Specifies the hash method to use for hashing the file content.
472
473### `[contenthash]`
474
475Type: `String`
476Default: `md5`
477
478Specifies the hash method to use for hashing the file content.
479
480### `[<hashType>:hash:<digestType>:<length>]`
481
482Type: `String`
483
484The hash of options.content (Buffer) (by default it's the hex digest of the hash).
485
486#### `digestType`
487
488Type: `String`
489Default: `'hex'`
490
491The [digest](https://en.wikipedia.org/wiki/Cryptographic_hash_function) that the
492hash function should use. Valid values include: base26, base32, base36,
493base49, base52, base58, base62, base64, and hex.
494
495#### `hashType`
496
497Type: `String`
498Default: `'md5'`
499
500The type of hash that the has function should use. Valid values include: `md5`,
501`sha1`, `sha256`, and `sha512`.
502
503#### `length`
504
505Type: `Number`
506Default: `undefined`
507
508Users may also specify a length for the computed hash.
509
510### `[N]`
511
512Type: `String`
513Default: `undefined`
514
515The n-th match obtained from matching the current file name against the `regExp`.
516
517## Examples
518
519### Names
520
521The following examples show how one might use `file-loader` and what the result would be.
522
523**file.js**
524
525```js
526import png from './image.png';
527```
528
529**webpack.config.js**
530
531```js
532module.exports = {
533 module: {
534 rules: [
535 {
536 test: /\.(png|jpe?g|gif)$/i,
537 use: [
538 {
539 loader: 'file-loader',
540 options: {
541 name: 'dirname/[contenthash].[ext]',
542 },
543 },
544 ],
545 },
546 ],
547 },
548};
549```
550
551Result:
552
553```bash
554# result
555dirname/0dcbbaa701328ae351f.png
556```
557
558---
559
560**file.js**
561
562```js
563import png from './image.png';
564```
565
566**webpack.config.js**
567
568```js
569module.exports = {
570 module: {
571 rules: [
572 {
573 test: /\.(png|jpe?g|gif)$/i,
574 use: [
575 {
576 loader: 'file-loader',
577 options: {
578 name: '[sha512:hash:base64:7].[ext]',
579 },
580 },
581 ],
582 },
583 ],
584 },
585};
586```
587
588Result:
589
590```bash
591# result
592gdyb21L.png
593```
594
595---
596
597**file.js**
598
599```js
600import png from './path/to/file.png';
601```
602
603**webpack.config.js**
604
605```js
606module.exports = {
607 module: {
608 rules: [
609 {
610 test: /\.(png|jpe?g|gif)$/i,
611 use: [
612 {
613 loader: 'file-loader',
614 options: {
615 name: '[path][name].[ext]?[contenthash]',
616 },
617 },
618 ],
619 },
620 ],
621 },
622};
623```
624
625Result:
626
627```bash
628# result
629path/to/file.png?e43b20c069c4a01867c31e98cbce33c9
630```
631
632### CDN
633
634The following examples show how to use `file-loader` for CDN uses query params.
635
636**file.js**
637
638```js
639import png from './directory/image.png?width=300&height=300';
640```
641
642**webpack.config.js**
643
644```js
645module.exports = {
646 output: {
647 publicPath: 'https://cdn.example.com/',
648 },
649 module: {
650 rules: [
651 {
652 test: /\.(png|jpe?g|gif)$/i,
653 use: [
654 {
655 loader: 'file-loader',
656 options: {
657 name: '[path][name].[ext][query]',
658 },
659 },
660 ],
661 },
662 ],
663 },
664};
665```
666
667Result:
668
669```bash
670# result
671https://cdn.example.com/directory/image.png?width=300&height=300
672```
673
674### Dynamic public path depending on environment variable at run time
675
676An 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__`.
677
678**main.js**
679
680```js
681const assetPrefixForNamespace = (namespace) => {
682 switch (namespace) {
683 case 'prod':
684 return 'https://cache.myserver.net/web';
685 case 'uat':
686 return 'https://cache-uat.myserver.net/web';
687 case 'st':
688 return 'https://cache-st.myserver.net/web';
689 case 'dev':
690 return 'https://cache-dev.myserver.net/web';
691 default:
692 return '';
693 }
694};
695const namespace = process.env.NAMESPACE;
696
697__webpack_public_path__ = `${assetPrefixForNamespace(namespace)}/`;
698```
699
700**file.js**
701
702```js
703import png from './image.png';
704```
705
706**webpack.config.js**
707
708```js
709module.exports = {
710 module: {
711 rules: [
712 {
713 test: /\.(png|jpg|gif)$/i,
714 loader: 'file-loader',
715 options: {
716 name: '[name].[contenthash].[ext]',
717 outputPath: 'static/assets/',
718 publicPath: 'static/assets/',
719 postTransformPublicPath: (p) => `__webpack_public_path__ + ${p}`,
720 },
721 },
722 ],
723 },
724};
725```
726
727Result when run with `NAMESPACE=prod` env variable:
728
729```bash
730# result
731https://cache.myserver.net/web/static/assets/image.somehash.png
732```
733
734Result when run with `NAMESPACE=dev` env variable:
735
736```bash
737# result
738https://cache-dev.myserver.net/web/static/assets/image.somehash.png
739```
740
741## Contributing
742
743Please take a moment to read our contributing guidelines if you haven't yet done so.
744
745[CONTRIBUTING](./.github/CONTRIBUTING.md)
746
747## License
748
749[MIT](./LICENSE)
750
751[npm]: https://img.shields.io/npm/v/file-loader.svg
752[npm-url]: https://npmjs.com/package/file-loader
753[node]: https://img.shields.io/node/v/file-loader.svg
754[node-url]: https://nodejs.org
755[deps]: https://david-dm.org/webpack-contrib/file-loader.svg
756[deps-url]: https://david-dm.org/webpack-contrib/file-loader
757[tests]: https://dev.azure.com/webpack-contrib/file-loader/_apis/build/status/webpack-contrib.file-loader?branchName=master
758[tests-url]: https://dev.azure.com/webpack-contrib/file-loader/_build/latest?definitionId=2&branchName=master
759[cover]: https://codecov.io/gh/webpack-contrib/file-loader/branch/master/graph/badge.svg
760[cover-url]: https://codecov.io/gh/webpack-contrib/file-loader
761[chat]: https://img.shields.io/badge/gitter-webpack%2Fwebpack-brightgreen.svg
762[chat-url]: https://gitter.im/webpack/webpack
763[size]: https://packagephobia.now.sh/badge?p=file-loader
764[size-url]: https://packagephobia.now.sh/result?p=file-loader