UNPKG

2.97 kBJavaScriptView Raw
1const { getConfig } = require('./config');
2const { detectLoaders, getNumOptimizationLoadersInstalled, appendLoaders } = require('./loaders');
3const { showWarning } = require('./migrater');
4
5/**
6 * Configure webpack and next.js to handle and optimize images with this plugin.
7 *
8 * @param {object} nextConfig - configuration, see the readme for possible values
9 * @param {object} nextComposePlugins - additional information when loaded with next-compose-plugins
10 * @returns {object}
11 */
12const withOptimizedImages = (nextConfig = {}, nextComposePlugins = {}) => {
13 const { optimizeImages, optimizeImagesInDev, overwriteImageLoaderPaths } = getConfig(nextConfig);
14
15 return Object.assign({}, nextConfig, {
16 webpack(config, options) {
17 if (!options.defaultLoaders) {
18 throw new Error(
19 'This plugin is not compatible with Next.js versions below 5.0.0 https://err.sh/next-plugins/upgrade',
20 );
21 }
22
23 const { dev, isServer } = options;
24 let enrichedConfig = config;
25
26 // detect all installed loaders
27 const detectedLoaders = detectLoaders(overwriteImageLoaderPaths);
28
29 // check if it should optimize images in the current step
30 const optimizeInCurrentStep = nextComposePlugins && typeof nextComposePlugins.phase === 'string'
31 ? (
32 (nextComposePlugins.phase === 'phase-production-build' && optimizeImages)
33 || (nextComposePlugins.phase === 'phase-export' && optimizeImages)
34 || (nextComposePlugins.phase === 'phase-development-server' && optimizeImagesInDev)
35 )
36 : ((!dev && optimizeImages) || (dev && optimizeImagesInDev));
37
38 // show a warning if images should get optimized but no loader is installed
39 if (optimizeImages && getNumOptimizationLoadersInstalled(detectedLoaders) === 0 && isServer) {
40 showWarning();
41 }
42
43 // remove (unoptimized) builtin image processing introduced in next.js 9.2
44 if (enrichedConfig.module.rules) {
45 enrichedConfig.module.rules.forEach((rule) => {
46 if (rule.oneOf) {
47 rule.oneOf.forEach((subRule) => {
48 if (
49 subRule.issuer && !subRule.test && !subRule.include && subRule.exclude
50 && subRule.use && subRule.use.options && subRule.use.options.name
51 ) {
52 if (String(subRule.issuer.test) === '/\\.(css|scss|sass)$/' && subRule.use.options.name.startsWith('static/media/')) {
53 subRule.exclude.push(/\.(jpg|jpeg|png|svg|webp|gif|ico)$/);
54 }
55 }
56 });
57 }
58 });
59 }
60
61 // append loaders
62 enrichedConfig = appendLoaders(enrichedConfig, getConfig(nextConfig), detectedLoaders,
63 isServer, optimizeInCurrentStep);
64
65 if (typeof nextConfig.webpack === 'function') {
66 return nextConfig.webpack(enrichedConfig, options);
67 }
68
69 return enrichedConfig;
70 },
71 });
72};
73
74module.exports = withOptimizedImages;