forked from cyrilwanner/optimized-images-loader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
processLoaders.ts
167 lines (144 loc) · 6.02 KB
/
processLoaders.ts
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
import urlLoader from 'url-loader';
import { loader } from 'webpack';
import { ImageOptions } from './parseQuery';
import { defaultFurtherLoaderOptions, OptionObject } from './options';
/**
* Enrich previous loader result with new information
*
* @param {string | string[]} result Previous loader result
* @param {{ width?: number; height?: number; format?: string }} originalImageInfo Metadata of original image
* @param {ImageOptions} imageOptions Image options
* @returns {string} Enriched result
*/
const enrichResult = (
result: string | string[],
originalImageInfo: { width?: number; height?: number; format?: string },
imageOptions: ImageOptions,
): string => {
const width = imageOptions.resize ? imageOptions.width : originalImageInfo.width;
const height = imageOptions.resize ? imageOptions.height : originalImageInfo.height;
const format = imageOptions.convert ? imageOptions.convert : originalImageInfo.format;
// an array means it was not processed by the url-/file-loader and the result should still be an array
// instead of a string. so in this case, append the additional export information to the array prototype
if (Array.isArray(result)) {
return `var res=${JSON.stringify(result)};res.width=${width};res.height=${height};res.format=${JSON.stringify(
format || '',
)};module.exports = res;`;
}
if (result.indexOf('module.exports') < 0) {
throw new Error('Unexpected input');
}
const output = result.replace(/((module\.exports\s*=)\s*)([^\s].*[^;])(;$|$)/g, 'var src = $3;');
// return `${output}module.exports={src:src,width:${width},height:${height},format:${JSON.stringify(
// format || '',
// )},toString:function(){return src;}};`;
return `${output}module.exports=src;`;
};
/**
* Replace additional placeholders in the file name
*
* @param {string} name File name pattern
* @param {{ width?: number; height?: number; format?: string }} originalImageInfo Metadata of original image
* @param {ImageOptions} imageOptions Image options
* @returns {string} Replaced file name
*/
const replaceName = (
name: string,
originalImageInfo: { width?: number; height?: number; format?: string },
imageOptions: ImageOptions,
): string => {
return name
.replace(/\[width\]/g, `${imageOptions.width || originalImageInfo.width}`)
.replace(/\[height\]/g, `${imageOptions.height || originalImageInfo.height}`);
};
/**
* Convert the image into a component
*
* @param {string} image Processed image
* @param {{ width?: number; height?: number; format?: string }} originalImageInfo Metadata of original image
* @param {ImageOptions} imageOptions Image options
* @param {OptionObject} loaderOptions Loader options
*/
const convertToComponent = (
image: string,
originalImageInfo: { width?: number; height?: number; format?: string },
imageOptions: ImageOptions,
loaderOptions: OptionObject,
): string => {
if (imageOptions.component === 'react') {
const svgr = require('@svgr/core').default; // eslint-disable-line
const babel = require('@babel/core'); // eslint-disable-line
const code = svgr.sync(image, loaderOptions.svgr || {}, { componentName: 'SvgComponent' });
const transformed = babel.transformSync(code, {
caller: {
name: 'optimized-images-loader',
},
babelrc: false,
configFile: false,
presets: [
babel.createConfigItem(require('@babel/preset-react'), { type: 'preset' }), // eslint-disable-line
babel.createConfigItem([require('@babel/preset-env'), { modules: false }], { type: 'preset' }), // eslint-disable-line
],
});
return transformed.code;
}
throw new Error(`Unknown component type ${imageOptions.component}`);
};
/**
* Process further loaders (url-loader & file-loader)
*
* @param {loader.LoaderContext} context Optimized images loader context
* @param {Buffer | string} image Processed image
* @param {{ width?: number; height?: number; format?: string }} originalImageInfo Metadata of original image
* @param {ImageOptions} imageOptions Image options
* @param {OptionObject} loaderOptions Options for further loaders
* @returns {string} Processed loader output
*/
const processLoaders = (
context: loader.LoaderContext,
image: Buffer | string | string[],
originalImageInfo: { width?: number; height?: number; format?: string },
imageOptions: ImageOptions,
loaderOptions: OptionObject,
): string => {
// do not apply further loaders if not needed
if (imageOptions.processLoaders === false) {
// transform result to a component
if (imageOptions.component === 'react') {
return convertToComponent(image.toString(), originalImageInfo, imageOptions, loaderOptions);
}
if (Array.isArray(image)) {
return enrichResult(image, originalImageInfo, imageOptions);
}
const output = Buffer.isBuffer(image) ? image.toString() : image;
return enrichResult(`module.exports = ${JSON.stringify(output)}`, originalImageInfo, imageOptions);
}
// create options for further loaders (url-loader & file-loader)
const furtherLoaderOptions = {
...defaultFurtherLoaderOptions,
...loaderOptions,
esModule: false,
} as OptionObject;
// replace name
furtherLoaderOptions.name = replaceName(furtherLoaderOptions.name, originalImageInfo, imageOptions);
// change extension for converted images
if (imageOptions.convert && furtherLoaderOptions.name) {
furtherLoaderOptions.name =
furtherLoaderOptions.name.indexOf('[ext]') >= 0
? furtherLoaderOptions.name.replace('[ext]', imageOptions.convert)
: (furtherLoaderOptions.name += `.${imageOptions.convert}`);
}
// force inlining
if (imageOptions.forceInline) {
furtherLoaderOptions.limit = undefined;
// force url
} else if (imageOptions.forceUrl) {
furtherLoaderOptions.limit = -1;
}
// build new loader context
const furtherLoaderContext = { ...context, query: furtherLoaderOptions };
// get result of url-loader
const result = urlLoader.call(furtherLoaderContext, image);
return enrichResult(result, originalImageInfo, imageOptions);
};
export default processLoaders;