Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .changelog/postcss-watch-new-dependencies.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Fixed

- Ensure `@tailwindcss/postcss` rebuilds when a file changes that was just added with `@import`, `@config` or `@plugin`
90 changes: 90 additions & 0 deletions integrations/webpack/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,93 @@ test(
`)
},
)

test(
'webpack + PostCSS (watch): rebuilds when a newly imported file changes',
{
fs: {
'package.json': json`
{
"main": "./src/index.js",
"browser": "./src/index.js",
"dependencies": {
"css-loader": "^6",
"postcss": "^8",
"postcss-loader": "^7",
"webpack": "^5",
"webpack-cli": "^5",
"mini-css-extract-plugin": "^2",
"tailwindcss": "workspace:^",
"@tailwindcss/postcss": "workspace:^"
}
}
`,
'postcss.config.js': js`
/** @type {import('postcss-load-config').Config} */
module.exports = {
plugins: {
'@tailwindcss/postcss': {},
},
}
`,
'webpack.config.js': js`
let MiniCssExtractPlugin = require('mini-css-extract-plugin')

module.exports = {
output: {
clean: true,
},
plugins: [new MiniCssExtractPlugin()],
module: {
rules: [
{
test: /.css$/i,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader'],
},
],
},
}
`,
'src/index.js': js`import '../styles/index.css'`,
'src/index.html': html`
<div class="flex"></div>
`,
// The stylesheets are outside of `source(…)`, so the scanner doesn't
// report them as dependencies.
'styles/index.css': css` @import 'tailwindcss/utilities' source('../src'); `,
'styles/buttons.css': css`
.btn-1 {
color: red;
}
`,
},
},
async ({ fs, spawn, expect }) => {
let process = await spawn('pnpm webpack --mode=development --watch')
await process.onStdout((m) => m.includes('compiled successfully in'))

await fs.expectFileNotToContain('dist/main.css', ['.btn-1'])

// Import a new file, which needs a full rebuild
await fs.write(
'styles/index.css',
css`
@import 'tailwindcss/utilities' source('../src');
@import './buttons.css';
`,
)
await process.onStdout((m) => m.includes('compiled successfully in'))
await fs.expectFileToContain('dist/main.css', ['.btn-1'])

// A change to the new file should cause a rebuild
await fs.write(
'styles/buttons.css',
css`
.btn-2 {
color: blue;
}
`,
)
await fs.expectFileToContain('dist/main.css', ['.btn-2'])
},
)
58 changes: 58 additions & 0 deletions packages/@tailwindcss-postcss/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -518,6 +518,64 @@ test('does not register the input file as a dependency, even if it is passed in
})
})

describe('files that a full rebuild finds for the first time', () => {
let dir: string
beforeEach(async () => {
dir = await realpath(await mkdtemp(path.join(tmpdir(), 'tw-postcss')))
// The stylesheets are outside of `source(…)`, so the scanner doesn't report
// them as dependencies.
await mkdir(path.join(dir, 'src'))
await writeFile(path.join(dir, 'src/index.html'), `<div class="underline"></div>`)
await writeFile(path.join(dir, 'index.css'), `@tailwind utilities source('./src');`)
})
afterEach(() => rm(dir, { recursive: true, force: true }))

function dependencies(result: postcss.Result) {
return result.messages
.filter((message) => message.type === 'dependency')
.map((message) => path.relative(dir, message.file))
.filter((file) => file.endsWith('.css'))
}

test('are reported as dependencies of that build, once', async () => {
let from = path.join(dir, 'index.css')
let processor = postcss([tailwindcss({ base: dir, optimize: false })])

let first = await processor.process(await readFile(from, 'utf8'), { from })
expect(dependencies(first)).toEqual([])

// Ensure the mtime below is actually observed as a change.
await new Promise((resolve) => setTimeout(resolve, 10))

await writeFile(path.join(dir, 'buttons.css'), `.btn { color: red; }`)
await writeFile(from, `@import './buttons.css';\n@tailwind utilities source('./src');`)

let second = await processor.process(await readFile(from, 'utf8'), { from })
expect(second.css).toContain('.btn')
expect(dependencies(second)).toEqual(['buttons.css'])

let third = await processor.process(await readFile(from, 'utf8'), { from })
expect(dependencies(third)).toEqual(['buttons.css'])
})

test('are reported as dependencies of that build when it fails', async () => {
let from = path.join(dir, 'index.css')
let processor = postcss([tailwindcss({ base: dir, optimize: false })])

await processor.process(await readFile(from, 'utf8'), { from })

// Ensure the mtime below is actually observed as a change.
await new Promise((resolve) => setTimeout(resolve, 10))

await writeFile(path.join(dir, 'buttons.css'), `.btn { @apply this-class-does-not-exist; }`)
await writeFile(from, `@import './buttons.css';\n@tailwind utilities source('./src');`)

let failed = await processor.process(await readFile(from, 'utf8'), { from })
expect(failed.warnings().length).toBeGreaterThan(0)
expect(dependencies(failed)).toEqual(['buttons.css'])
})
})

describe('error recovery', () => {
let dir: string
beforeEach(async () => {
Expand Down
37 changes: 24 additions & 13 deletions packages/@tailwindcss-postcss/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,20 @@ function tailwindcss(opts: PluginOptions = {}): AcceptedPlugin {
// optimize the build by not creating the compiler until we need it.
let isInitialBuild = context.compiler === null

// Report each config file, plugin, etc. only once per build
let reportedDependencies = new Set<string>()
function addDependency(file: string) {
let absolutePath = path.resolve(file)
if (reportedDependencies.has(absolutePath)) return
reportedDependencies.add(absolutePath)
result.messages.push({
type: 'dependency',
plugin: '@tailwindcss/postcss',
file: absolutePath,
parent: result.opts.from,
})
}

async function createCompiler() {
DEBUG && I.start('Setup compiler')
if (context.fullRebuildPaths.length > 0 && !isInitialBuild) {
Expand Down Expand Up @@ -169,7 +183,14 @@ function tailwindcss(opts: PluginOptions = {}): AcceptedPlugin {
from: result.opts.from,
base: inputBasePath,
shouldRewriteUrls,
onDependency: (path) => context.fullRebuildPaths.push(path),
onDependency: (depPath) => {
context.fullRebuildPaths.push(depPath)

// A full rebuild can find files that the previous compiler didn't
// know about, like a new `@import`. Watch them right away, so a
// change to them causes a rebuild, also when this compile fails.
addDependency(depPath)
},
// In CSS Module files, we have to disable the `@property` polyfill since these will
// emit global `*` rules which are considered to be non-pure and will cause builds
// to fail.
Expand All @@ -196,12 +217,7 @@ function tailwindcss(opts: PluginOptions = {}): AcceptedPlugin {
DEBUG && I.start('Register full rebuild paths')
{
for (let file of context.fullRebuildPaths) {
result.messages.push({
type: 'dependency',
plugin: '@tailwindcss/postcss',
file: path.resolve(file),
parent: result.opts.from,
})
addDependency(file)
}

let files = result.messages.flatMap((message) => {
Expand Down Expand Up @@ -387,12 +403,7 @@ function tailwindcss(opts: PluginOptions = {}): AcceptedPlugin {
let resolvedInputFile = path.resolve(base, inputFile)

for (let file of context.fullRebuildPaths) {
result.messages.push({
type: 'dependency',
plugin: '@tailwindcss/postcss',
file: path.resolve(file),
parent: result.opts.from,
})
addDependency(file)
}

if (context.scanner) {
Expand Down