Skip to content

Commit 10f87e1

Browse files
committed
Fix PostCSS regression on remote examples
1 parent 41bdaee commit 10f87e1

File tree

1 file changed

+25
-4
lines changed
  • programs/develop/webpack/plugin-css/css-tools

1 file changed

+25
-4
lines changed

programs/develop/webpack/plugin-css/css-tools/postcss.ts

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,15 @@
77

88
import * as path from 'path'
99
import * as fs from 'fs'
10+
import {createRequire} from 'module'
1011
import * as messages from '../css-lib/messages'
11-
import {isUsingTailwind} from './tailwind'
12-
import {isUsingSass} from './sass'
13-
import {isUsingLess} from './less'
1412
import {
1513
installOptionalDependencies,
1614
hasDependency
1715
} from '../css-lib/integrations'
16+
import {isUsingTailwind} from './tailwind'
17+
import {isUsingSass} from './sass'
18+
import {isUsingLess} from './less'
1819
import type {StyleLoaderOptions} from '../common-style-loaders'
1920

2021
let userMessageDelivered = false
@@ -86,6 +87,22 @@ export async function maybeUsePostCss(
8687

8788
const userPostCssConfig = findPostCssConfig(projectPath)
8889

90+
// Resolve the project's own PostCSS implementation to avoid resolving from the toolchain
91+
function getProjectPostcssImpl(): any {
92+
try {
93+
const req = createRequire(path.join(projectPath, 'package.json'))
94+
return req('postcss')
95+
} catch {
96+
try {
97+
// Fallback to loader's postcss if not found in project
98+
// eslint-disable-next-line @typescript-eslint/no-var-requires
99+
return require('postcss')
100+
} catch {
101+
return undefined
102+
}
103+
}
104+
}
105+
89106
try {
90107
require.resolve('postcss-loader')
91108
} catch (e) {
@@ -108,9 +125,13 @@ export async function maybeUsePostCss(
108125
type: 'css',
109126
loader: require.resolve('postcss-loader'),
110127
options: {
128+
// Prefer the project's PostCSS implementation so plugins resolve from the project
129+
implementation: getProjectPostcssImpl(),
111130
postcssOptions: {
112131
ident: 'postcss',
113-
config: userPostCssConfig,
132+
// When the user has a config, pass the string path (tests rely on this being a string)
133+
// Otherwise, disable auto discovery to avoid resolving outside the project.
134+
config: userPostCssConfig ? userPostCssConfig : false,
114135
// If the user has their own PostCSS config, defer entirely to it.
115136
// Otherwise, apply a sensible default with postcss-preset-env.
116137
plugins: userPostCssConfig

0 commit comments

Comments
 (0)