Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save martinratinaud/dd9ab1c752d5301ad3bee9565f11fb6c to your computer and use it in GitHub Desktop.
Save martinratinaud/dd9ab1c752d5301ad3bee9565f11fb6c to your computer and use it in GitHub Desktop.
Modularize next config
import fs from 'fs';
import path from 'path';
const loadNextConfigs = async (rootFolder) => {
return (
await Promise.all(
fs
.readdirSync(rootFolder, { withFileTypes: true })
.filter((dirent) => dirent.isDirectory())
.map(async ({ name }) => {
const nextConfigPath = path.join(rootFolder, name, 'next.config.mjs');
if (!fs.existsSync(nextConfigPath)) {
return undefined;
}
console.info('->', nextConfigPath);
const { default: withConfig } = await import(
`../../${nextConfigPath}`
);
return withConfig;
})
)
).filter(Boolean);
};
const compose =
(...fns) =>
(arg) =>
fns.reduceRight((res, fn) => fn(res), arg);
const withConfig = async (
/** @type {import('next').NextConfig} */
nextConfig,
{ folders = ['./lib', './app'] } = {}
) => {
console.info('Loading next.config.mjs from', folders.join(', '));
const configFunctions = (
await Promise.all(folders.map(loadNextConfigs))
).flat();
return compose(...configFunctions)(nextConfig);
};
export default withConfig;
const withUpload = (
/** @type {import('next').NextConfig} */
nextConfig
) => {
return {
...nextConfig,
env: {
R2_ENDPOINT: process.env.R2_ENDPOINT,
R2_BUCKET: process.env.R2_BUCKET,
R2_PUBLIC_URL: process.env.R2_PUBLIC_URL,
...nextConfig.env,
},
images: {
...(nextConfig?.images || {}),
remotePatterns: [
...(nextConfig?.images?.remotePatterns || []),
{
protocol: 'https',
hostname: process.env.R2_PUBLIC_URL.replace('https://', ''),
},
],
},
};
};
export default withUpload;
import nextExtendableConfig from './lib/next-extendable-config/index.mjs';
/** @type {import('next').NextConfig} */
const nextConfig = {
env: {
SITE_NAME: process.env.SITE_NAME,
},
};
export default nextExtendableConfig(nextConfig, {
folders: ['./lib', './app'],
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment