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-)+outputPath
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: `md4`
470
471Specifies the hash method to use for hashing the file content.
472
473### `[contenthash]`
474
475Type: `String`
476Default: `md4`
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: `'md4'`
499
500The type of hash that the has function should use. Valid values include: `md4`, `md5`, `sha1`, `sha256`, and `sha512`.
501
502#### `length`
503
504Type: `Number`
505Default: `undefined`
506
507Users may also specify a length for the computed hash.
508
509### `[N]`
510
511Type: `String`
512Default: `undefined`
513
514The n-th match obtained from matching the current file name against the `regExp`.
515
516## Examples
517
518### Names
519
520The following examples show how one might use `file-loader` and what the result would be.
521
522**file.js**
523
524```js
525import png from './image.png';
526```
527
528**webpack.config.js**
529
530```js
531module.exports = {
532 module: {
533 rules: [
534 {
535 test: /\.(png|jpe?g|gif)$/i,
536 use: [
537 {
538 loader: 'file-loader',
539 options: {
540 name: 'dirname/[contenthash].[ext]',
541 },
542 },
543 ],
544 },
545 ],
546 },
547};
548```
549
550Result:
551
552```bash
553# result
554dirname/0dcbbaa701328ae351f.png
555```
556
557---
558
559**file.js**
560
561```js
562import png from './image.png';
563```
564
565**webpack.config.js**
566
567```js
568module.exports = {
569 module: {
570 rules: [
571 {
572 test: /\.(png|jpe?g|gif)$/i,
573 use: [
574 {
575 loader: 'file-loader',
576 options: {
577 name: '[sha512:hash:base64:7].[ext]',
578 },
579 },
580 ],
581 },
582 ],
583 },
584};
585```
586
587Result:
588
589```bash
590# result
591gdyb21L.png
592```
593
594---
595
596**file.js**
597
598```js
599import png from './path/to/file.png';
600```
601
602**webpack.config.js**
603
604```js
605module.exports = {
606 module: {
607 rules: [
608 {
609 test: /\.(png|jpe?g|gif)$/i,
610 use: [
611 {
612 loader: 'file-loader',
613 options: {
614 name: '[path][name].[ext]?[contenthash]',
615 },
616 },
617 ],
618 },
619 ],
620 },
621};
622```
623
624Result:
625
626```bash
627# result
628path/to/file.png?e43b20c069c4a01867c31e98cbce33c9
629```
630
631### CDN
632
633The following examples show how to use `file-loader` for CDN uses query params.
634
635**file.js**
636
637```js
638import png from './directory/image.png?width=300&height=300';
639```
640
641**webpack.config.js**
642
643```js
644module.exports = {
645 output: {
646 publicPath: 'https://cdn.example.com/',
647 },
648 module: {
649 rules: [
650 {
651 test: /\.(png|jpe?g|gif)$/i,
652 use: [
653 {
654 loader: 'file-loader',
655 options: {
656 name: '[path][name].[ext][query]',
657 },
658 },
659 ],
660 },
661 ],
662 },
663};
664```
665
666Result:
667
668```bash
669# result
670https://cdn.example.com/directory/image.png?width=300&height=300
671```
672
673### Dynamic public path depending on environment variable at run time
674
675An 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 differently 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__`.
676
677**main.js**
678
679```js
680const assetPrefixForNamespace = (namespace) => {
681 switch (namespace) {
682 case 'prod':
683 return 'https://cache.myserver.net/web';
684 case 'uat':
685 return 'https://cache-uat.myserver.net/web';
686 case 'st':
687 return 'https://cache-st.myserver.net/web';
688 case 'dev':
689 return 'https://cache-dev.myserver.net/web';
690 default:
691 return '';
692 }
693};
694const namespace = process.env.NAMESPACE;
695
696__webpack_public_path__ = `${assetPrefixForNamespace(namespace)}/`;
697```
698
699**file.js**
700
701```js
702import png from './image.png';
703```
704
705**webpack.config.js**
706
707```js
708module.exports = {
709 module: {
710 rules: [
711 {
712 test: /\.(png|jpg|gif)$/i,
713 loader: 'file-loader',
714 options: {
715 name: '[name].[contenthash].[ext]',
716 outputPath: 'static/assets/',
717 publicPath: 'static/assets/',
718 postTransformPublicPath: (p) => `__webpack_public_path__ + ${p}`,
719 },
720 },
721 ],
722 },
723};
724```
725
726Result when run with `NAMESPACE=prod` env variable:
727
728```bash
729# result
730https://cache.myserver.net/web/static/assets/image.somehash.png
731```
732
733Result when run with `NAMESPACE=dev` env variable:
734
735```bash
736# result
737https://cache-dev.myserver.net/web/static/assets/image.somehash.png
738```
739
740## Contributing
741
742Please take a moment to read our contributing guidelines if you haven't yet done so.
743
744[CONTRIBUTING](./.github/CONTRIBUTING.md)
745
746## License
747
748[MIT](./LICENSE)
749
750[npm]: https://img.shields.io/npm/v/file-loader.svg
751[npm-url]: https://npmjs.com/package/file-loader
752[node]: https://img.shields.io/node/v/file-loader.svg
753[node-url]: https://nodejs.org
754[deps]: https://david-dm.org/webpack-contrib/file-loader.svg
755[deps-url]: https://david-dm.org/webpack-contrib/file-loader
756[tests]: https://github.com/webpack-contrib/file-loader/workflows/file-loader/badge.svg
757[tests-url]: https://github.com/webpack-contrib/file-loader/actions
758[cover]: https://codecov.io/gh/webpack-contrib/file-loader/branch/master/graph/badge.svg
759[cover-url]: https://codecov.io/gh/webpack-contrib/file-loader
760[chat]: https://img.shields.io/badge/gitter-webpack%2Fwebpack-brightgreen.svg
761[chat-url]: https://gitter.im/webpack/webpack
762[size]: https://packagephobia.now.sh/badge?p=file-loader
763[size-url]: https://packagephobia.now.sh/result?p=file-loader