1 | const { getConfig } = require('./config');
|
2 | const { detectLoaders, getNumOptimizationLoadersInstalled, appendLoaders } = require('./loaders');
|
3 | const { showWarning } = require('./migrater');
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 | const 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 |
|
27 | const detectedLoaders = detectLoaders(overwriteImageLoaderPaths);
|
28 |
|
29 |
|
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 |
|
39 | if (optimizeImages && getNumOptimizationLoadersInstalled(detectedLoaders) === 0 && isServer) {
|
40 | showWarning();
|
41 | }
|
42 |
|
43 |
|
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 |
|
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 |
|
74 | module.exports = withOptimizedImages;
|