From 1e10cd0c5fa7873e3da5846152c9028823eb4c59 Mon Sep 17 00:00:00 2001 From: Sam Brodie Date: Wed, 31 Jul 2024 16:37:11 -0400 Subject: [PATCH] feat: modify image config depending on next version --- .../next/src/config/withHeadstartWPConfig.ts | 44 ++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/packages/next/src/config/withHeadstartWPConfig.ts b/packages/next/src/config/withHeadstartWPConfig.ts index 23106075e..cb4e1cacf 100644 --- a/packages/next/src/config/withHeadstartWPConfig.ts +++ b/packages/next/src/config/withHeadstartWPConfig.ts @@ -1,8 +1,20 @@ import { ConfigError, HeadlessConfig } from '@headstartwp/core'; import { NextConfig } from 'next'; import fs from 'fs'; +import path from 'path'; import { ModifySourcePlugin, ConcatOperation } from './plugins/ModifySourcePlugin'; +// Get the path to the project's root package.json +const packageJsonPath = path.join(process.cwd(), 'package.json'); +const packageJson = packageJsonPath ? JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')) : {}; + +type RemotePattern = { + protocol?: 'http' | 'https'; + hostname: string; + port?: string; + pathname?: string; +}; + const LINARIA_EXTENSION = '.linaria.module.css'; const isPackageInstalled = (packageName: string): boolean => { @@ -47,6 +59,21 @@ function traverse(rules) { } } +function meetsMinimumVersion(versionString: string, compareVersion: number): boolean { + if (versionString === 'latest') { + return true; + } + + // Remove the prefix (^, >=) from the version string + const cleanedVersion = versionString.replace(/^[^\d]*/, ''); + + // Split the version into major, minor, and patch components + const [major] = cleanedVersion.split('.').map(Number); + + // Compare the major version number + return major >= compareVersion; +} + /** * HOC used to wrap the nextjs config object with the headless config object. * @@ -121,11 +148,26 @@ export function withHeadstartWPConfig( } }); + const useImageRemotePatterns = meetsMinimumVersion(packageJson?.dependencies?.next, 14); + const imageConfig: { domains?: string[]; remotePatterns?: RemotePattern[] } = {}; + + if (useImageRemotePatterns) { + imageConfig.remotePatterns = + nextConfig.remotePatterns ?? + imageDomains.map((each) => { + return { + hostname: each, + }; + }); + } else { + imageConfig.domains = imageDomains; + } + const config: NextConfig = { ...nextConfig, images: { ...nextConfig.images, - domains: imageDomains, + ...imageConfig, }, async rewrites() { const rewrites =