Tengo un proyecto nextjs en el que estoy usando tailwind. En la compilación, cargo una configuración predeterminada, pero luego también quiero esperar una respuesta de la API para obtener estilos personalizados desde un punto final.
Esto es lo que tengo a continuación, sin embargo, siento que estoy haciendo esto de manera incorrecta, actualmente obtengo errores de paquete web:
Error: No se puede encontrar el módulo './services/getThemeStyles'
// ./tailwind.config.js // Default styles const theme = require('./lib/themes/default/tailwind/tailwind.config'); // Website custom styles const custom = require('./services/getThemeStyles'); module.exports = { ...theme, // Do deep merge here of theme and custom content: ['./lib/**/*.{js,ts,jsx,tsx}', './pages/**/*.{js,ts,jsx,tsx}', './components/**/*.{js,ts,jsx,tsx}'], }; // ./services/getThemeStyles.ts // Fake temp endpoint, this would hit an API when working. const theme = require('/data/theme'); export default async function getThemeStyles(): Promise<any> { return new Promise((resolve) => { setTimeout(() => { resolve(theme); }, 1); }); } // ./data/theme.ts const Theme = { extend: { colors: { 'banner-background': 'rgb(220,220,0)' } } } export default Theme;¿Alguien ha hecho esto antes o alguien puede ayudarme?
Cambié mi enfoque, hice un servidor de nodos para que obtener datos sea más realista, así que ahora mi tailwind.config.js se ve así:
const fetch = require('node-fetch'); const merge = require('merge-deep'); module.exports = (async function() { let theme = require('./lib/themes/default/tailwind/tailwind.config'); const response = await fetch('http://localhost:5000/data'); const data = await response.json(); return { ...merge(theme, data), content: ['./lib/**/*.{js,ts,jsx,tsx}', './pages/**/*.{js,ts,jsx,tsx}', './components/**/*.{js,ts,jsx,tsx}'], } })(); Sin embargo, no puedo poner await delante de fetch debido a que no estoy en una función asíncrona, por lo que el módulo se exporta antes de que se devuelva la solicitud.
¡Encontré una solución, en caso de que alguien más esté tratando de hacer esto también!
Simplemente use un complemento siguiente (podría ser posible sin el complemento) para descargar el archivo antes de compilarlo, luego importe este archivo dentro de la configuración de Tailwind.
El único problema es que hay un bucle infinito cuando se intenta ejecutar el next dev desarrollo, así que solo extraiga el archivo cuando se construya para la producción.
Pero para mi caso de uso, esto está bien.
// next.config.js const WebpackBeforeBuildPlugin = require('before-build-webpack'); const fs = require('fs'); /** @type {import('next').NextConfig} */ const nextConfig = { reactStrictMode: true, webpack: (config, options) => { if (process.env.NODE_ENV === 'development') { return config; } // Important: return the modified config config.plugins.push(new WebpackBeforeBuildPlugin(async function(stats, callback) { const response = await fetch("http://localhost:5000/data"); const dt = await response.json(); fs.writeFileSync('./.tmp/custom.json', JSON.stringify(dt)); callback(); })) return config; }, }; module.exports = nextConfig; // tailwind.config.js const merge = require('merge-deep'); const theme = require('./lib/themes/default/tailwind/tailwind.config'); let custom = null; // Try and merge any custom styles with the selected theme try { custom = require('./.tmp/custom.json'); } catch (e) { custom = []; } module.exports = { ...merge(theme, custom), content: ['./lib/**/*.{js,ts,jsx,tsx}', './pages/**/*.{js,ts,jsx,tsx}', './components/**/*.{js,ts,jsx,tsx}'], };