-
-
Notifications
You must be signed in to change notification settings - Fork 9.8k
NextJS-Vite: Automatically fix bad PostCSS configuration #32691
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
1cafff7
Enhance PostCSS configuration handling
ndelangen 0dc191c
replace the incorrect postcss config file syntax with the correct one
ndelangen d86e68a
Update PostCSS configuration handling and add YAML dependency
ndelangen 4ad2494
Merge branch 'next' into norbert/postcss-config-modification
ndelangen c874228
Refactor PostCSS config loader by removing YAML support
ndelangen 857bfc4
Remove YAML dependency from Next.js Vite package configuration and up…
ndelangen File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,139 @@ | ||
| import { readFile, writeFile } from 'node:fs/promises'; | ||
| import { createRequire } from 'node:module'; | ||
|
|
||
| import { getProjectRoot } from 'storybook/internal/common'; | ||
| import { IncompatiblePostCssConfigError } from 'storybook/internal/server-errors'; | ||
|
|
||
| import config from 'lilconfig'; | ||
| import postCssLoadConfig from 'postcss-load-config'; | ||
|
|
||
| type Options = import('lilconfig').Options; | ||
|
|
||
| const require = createRequire(import.meta.url); | ||
|
|
||
| async function loader(filepath: string) { | ||
| return require(filepath); | ||
| } | ||
|
|
||
| const withLoaders = (options: Options = {}) => { | ||
| const moduleName = 'postcss'; | ||
|
|
||
| return { | ||
| ...options, | ||
| loaders: { | ||
| ...options.loaders, | ||
| '.cjs': loader, | ||
| '.cts': loader, | ||
| '.js': loader, | ||
| '.mjs': loader, | ||
| '.mts': loader, | ||
| '.ts': loader, | ||
| }, | ||
| searchPlaces: [ | ||
| ...(options.searchPlaces ?? []), | ||
| 'package.json', | ||
| `.${moduleName}rc`, | ||
| `.${moduleName}rc.json`, | ||
| `.${moduleName}rc.ts`, | ||
| `.${moduleName}rc.cts`, | ||
| `.${moduleName}rc.mts`, | ||
| `.${moduleName}rc.js`, | ||
| `.${moduleName}rc.cjs`, | ||
| `.${moduleName}rc.mjs`, | ||
| `${moduleName}.config.ts`, | ||
| `${moduleName}.config.cts`, | ||
| `${moduleName}.config.mts`, | ||
| `${moduleName}.config.js`, | ||
| `${moduleName}.config.cjs`, | ||
| `${moduleName}.config.mjs`, | ||
| ], | ||
| } satisfies Options; | ||
| }; | ||
|
|
||
| /** | ||
| * Find PostCSS config file path (without loading the config) | ||
| * | ||
| * @param {String} path Config Path | ||
| * @param {Object} options Config Options | ||
| * @returns {Promise<string | null>} Config file path or null if not found | ||
| */ | ||
| async function postCssFindConfig(path: string, options: Options = {}) { | ||
| const result = await config.lilconfig('postcss', withLoaders(options)).search(path); | ||
|
|
||
| return result ? result.filepath : null; | ||
| } | ||
|
|
||
| export { postCssLoadConfig }; | ||
|
|
||
| /** | ||
| * Normalizes PostCSS configuration for NextJS compatibility. | ||
| * | ||
| * This function handles the incompatibility between NextJS's PostCSS plugin format and Storybook's | ||
| * requirements. NextJS uses array format for plugins while Storybook expects object format. | ||
| * | ||
| * Process: | ||
| * | ||
| * 1. First attempts to load the config as-is | ||
| * 2. If that fails due to "Invalid PostCSS Plugin found" error, modifies the config file to convert | ||
| * array format to object format (e.g., ["@tailwindcss/postcss"] becomes { | ||
| * "@tailwindcss/postcss": {} }) | ||
| * 3. Retries loading with the modified config | ||
| * | ||
| * @param searchPath - Directory path to search for PostCSS config | ||
| * @returns Promise<boolean> - true if config loads successfully (or no config found), false if | ||
| * config exists but cannot be loaded | ||
| * @throws {IncompatiblePostCssConfigError} - When config cannot be fixed automatically | ||
| * @sideEffect Modifies the PostCSS config file on disk when fixing plugin format | ||
| */ export const normalizePostCssConfig = async (searchPath: string): Promise<boolean> => { | ||
| const configPath = await postCssFindConfig(searchPath); | ||
| if (!configPath) { | ||
| return true; | ||
| } | ||
|
|
||
| let error: Error | undefined; | ||
|
|
||
| // First attempt: try loading config as-is | ||
| try { | ||
| await postCssLoadConfig({}, searchPath, { stopDir: getProjectRoot() }); | ||
| return true; // Success! | ||
| } catch (e: unknown) { | ||
| if (e instanceof Error) { | ||
| error = e; | ||
| } | ||
| } | ||
|
|
||
| if (!error) { | ||
| return true; | ||
| } | ||
|
|
||
| // No config found is not an error we need to handle | ||
| if (error.message.includes('No PostCSS Config found')) { | ||
| return true; | ||
| } | ||
|
|
||
| // NextJS uses an incompatible format for PostCSS plugins, we make an attempt to fix it | ||
| if (error.message.includes('Invalid PostCSS Plugin found')) { | ||
| // Second attempt: try with modified config | ||
| const originalContent = await readFile(configPath, 'utf8'); | ||
| try { | ||
| const modifiedContent = originalContent.replace( | ||
| 'plugins: ["@tailwindcss/postcss"]', | ||
| 'plugins: { "@tailwindcss/postcss": {} }' | ||
| ); | ||
ndelangen marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| // Write the modified content | ||
| await writeFile(configPath, modifiedContent, 'utf8'); | ||
|
|
||
| // Retry loading the config | ||
| await postCssLoadConfig({}, searchPath, { stopDir: getProjectRoot() }); | ||
| return true; // Success with modified config! | ||
| } catch (e: any) { | ||
| // We were unable to fix the config, so we change the file back to the original content | ||
| await writeFile(configPath, originalContent, 'utf8'); | ||
| // and throw an error | ||
| throw new IncompatiblePostCssConfigError({ error }); | ||
| } | ||
ndelangen marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| return false; | ||
| }; | ||
ndelangen marked this conversation as resolved.
Show resolved
Hide resolved
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This approach will not work for
ymlfiles.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I do not think we need it.
I had to copy code from here:
https://github.com/postcss/postcss-load-config/blob/main/src/index.js
And i wanted to keep it close to the original code.
yamlis already included in the bundle.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If we don't support modifying YAML-based PostCSS files, we should clean up the code above (searching for YAML files, registering a YAML config loader,...). Then we can also actually remove the
yamldependency.Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You would rather not keep the code similar to where we got it from? Okay.
Their code seems to prefer yaml config files, so our code skipping/not looking for them, might cause their code to find different files, if the user has many different ones, possibly on multiple levels.
The replacement code, also does not "work" for JSON files, should I remove handling for those as well?