forked from webpack-contrib/url-loader
/
index.js
78 lines (60 loc) · 2.11 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
67
68
69
70
71
72
73
74
75
76
77
78
import path from 'path';
import { getOptions } from 'loader-utils';
import validateOptions from 'schema-utils';
import mime from 'mime-types';
import normalizeFallback from './utils/normalizeFallback';
import schema from './options.json';
function shouldTransform(limit, size) {
if (typeof limit === 'boolean') {
return limit;
}
if (typeof limit === 'string') {
return size <= parseInt(limit, 10);
}
if (typeof limit === 'number') {
return size <= limit;
}
return true;
}
export default function loader(src) {
// Loader Options
const options = getOptions(this) || {};
validateOptions(schema, options, {
name: 'URL Loader',
baseDataPath: 'options',
});
// No limit or within the specified limit
if (shouldTransform(options.limit, src.length)) {
const file = this.resourcePath;
const mimetype = options.mimetype || mime.contentType(path.extname(file));
const encoding = options.encoding || 'base64';
if (typeof src === 'string') {
// eslint-disable-next-line no-param-reassign
src = Buffer.from(src);
}
const esModule =
typeof options.esModule !== 'undefined' ? options.esModule : true;
const encodedData = options.source
? options.source(src.toString())
: `data:${mimetype || ''};${encoding},${src.toString(encoding)}`;
return `${
esModule ? 'export default' : 'module.exports ='
} ${JSON.stringify(encodedData)}`;
}
// Normalize the fallback.
const {
loader: fallbackLoader,
options: fallbackOptions,
} = normalizeFallback(options.fallback, options);
// Require the fallback.
// eslint-disable-next-line global-require, import/no-dynamic-require
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;