This repository has been archived by the owner on Mar 17, 2021. It is now read-only.
/
index.js
66 lines (52 loc) · 1.71 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/* eslint-disable
global-require,
no-param-reassign,
prefer-destructuring,
import/no-dynamic-require,
*/
import { getOptions } from 'loader-utils';
import validateOptions from 'schema-utils';
import mime from 'mime';
import normalizeFallback from './utils/normalizeFallback';
import schema from './options.json';
function shouldTransform(limit, size) {
if (typeof limit === 'boolean') {
return limit;
}
if (typeof limit === 'number' || typeof limit === 'string') {
return size <= parseInt(limit, 10);
}
return true;
}
export default function loader(src) {
// Loader Options
const options = getOptions(this) || {};
validateOptions(schema, options, 'URL Loader');
// No limit or within the specified limit
if (shouldTransform(options.limit, src.length)) {
const file = this.resourcePath;
// Get MIME type
const mimetype = options.mimetype || mime.getType(file);
if (typeof src === 'string') {
src = Buffer.from(src);
}
return `module.exports = ${JSON.stringify(
`data:${mimetype || ''};base64,${src.toString('base64')}`
)}`;
}
// Normalize the fallback.
const {
loader: fallbackLoader,
options: fallbackOptions,
} = normalizeFallback(options.fallback, options);
// Require the fallback.
const fallback = require(fallbackLoader);
// Call the fallback, passing a copy of the loader context. The copy has the query replaced. This way, the fallback
// loader receives the query which was intended for it instead of the query which was intended for url-loader.
const fallbackLoaderContext = Object.assign({}, this, {
query: fallbackOptions,
});
return fallback.call(fallbackLoaderContext, src);
}
// Loader Mode
export const raw = true;