forked from cyrilwanner/next-optimized-images
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
74 lines (63 loc) 路 2.95 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
const { getConfig } = require('./config');
const { detectLoaders, getNumOptimizationLoadersInstalled, appendLoaders } = require('./loaders');
const { showWarning } = require('./migrater');
/**
* Configure webpack and next.js to handle and optimize images with this plugin.
*
* @param {object} nextConfig - configuration, see the readme for possible values
* @param {object} nextComposePlugins - additional information when loaded with next-compose-plugins
* @returns {object}
*/
const withOptimizedImages = (nextConfig = {}, nextComposePlugins = {}) => {
const { optimizeImages, optimizeImagesInDev, overwriteImageLoaderPaths } = getConfig(nextConfig);
return Object.assign({}, nextConfig, {
webpack(config, options) {
if (!options.defaultLoaders) {
throw new Error(
'This plugin is not compatible with Next.js versions below 5.0.0 https://err.sh/next-plugins/upgrade',
);
}
const { dev, isServer } = options;
let enrichedConfig = config;
// detect all installed loaders
const detectedLoaders = detectLoaders(overwriteImageLoaderPaths);
// check if it should optimize images in the current step
const optimizeInCurrentStep = nextComposePlugins && typeof nextComposePlugins.phase === 'string'
? (
(nextComposePlugins.phase === 'phase-production-build' && optimizeImages)
|| (nextComposePlugins.phase === 'phase-export' && optimizeImages)
|| (nextComposePlugins.phase === 'phase-development-server' && optimizeImagesInDev)
)
: ((!dev && optimizeImages) || (dev && optimizeImagesInDev));
// show a warning if images should get optimized but no loader is installed
if (optimizeImages && getNumOptimizationLoadersInstalled(detectedLoaders) === 0 && isServer) {
showWarning();
}
// remove (unoptimized) builtin image processing introduced in next.js 9.2
if (enrichedConfig.module.rules) {
enrichedConfig.module.rules.forEach((rule) => {
if (rule.oneOf) {
rule.oneOf.forEach((subRule) => {
if (
subRule.issuer && !subRule.test && !subRule.include && subRule.exclude
&& subRule.use && subRule.use.options && subRule.use.options.name
) {
if ((String(subRule.issuer.test) === '/\\.(css|scss|sass)$/' || String(subRule.issuer) === '/\\.(css|scss|sass)$/') && subRule.use.options.name.startsWith('static/media/')) {
subRule.exclude.push(/\.(jpg|jpeg|png|svg|webp|gif|ico)$/);
}
}
});
}
});
}
// append loaders
enrichedConfig = appendLoaders(enrichedConfig, getConfig(nextConfig), detectedLoaders,
isServer, optimizeInCurrentStep);
if (typeof nextConfig.webpack === 'function') {
return nextConfig.webpack(enrichedConfig, options);
}
return enrichedConfig;
},
});
};
module.exports = withOptimizedImages;