Skip to content

Commit

Permalink
feat: modify image config depending on next version
Browse files Browse the repository at this point in the history
  • Loading branch information
sambrodie committed Jul 31, 2024
1 parent 14c398d commit 1e10cd0
Showing 1 changed file with 43 additions and 1 deletion.
44 changes: 43 additions & 1 deletion packages/next/src/config/withHeadstartWPConfig.ts
Original file line number Diff line number Diff line change
@@ -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 => {
Expand Down Expand Up @@ -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.
*
Expand Down Expand Up @@ -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 =
Expand Down

0 comments on commit 1e10cd0

Please sign in to comment.