withastro / astro

The web framework for content-driven websites. ⭐️ Star to support our work!
https://astro.build
Other
46.79k stars 2.49k forks source link

Astro with Tailwind imports CSS from 404.astro #8549

Closed LefanTan closed 1 year ago

LefanTan commented 1 year ago

Astro Info

Astro                    v3.0.13
Node                     v18.17.1
System                   macOS (arm64)
Package Manager          npm
Output                   server
Adapter                  @astrojs/node
Integrations             none

If this issue only occurs in one browser, which browser is a problem?

No response

Describe the Bug

When tailwind is installed and a 404.astro page is present, the build version of the project will always include the CSS files from the 404 page in all the pages. Depending on the file size of 404's CSS, this can have a downstream effect on load performance

When visiting /, I don't think stylesheets related to 404.css should be imported. Screen Shot 2023-09-13 at 3 24 04 PM

I've noticed that this could also happened to nested 404 pages, though i'm unable to replicate it in the sandbox

What's the expected result?

Stylesheet related to 404 shouldn't be imported when visiting normal pages.

Link to Minimal Reproducible Example

https://codesandbox.io/p/sandbox/withered-snowflake-zmv8rm?file=/src/pages/nested/404.astro:9,1

Participation

BryceRussell commented 1 year ago

This is expected behavior, when CSS is bundled into a file it is named after the first page it is used on and the tailwind integration injects styles onto every page by default so 404 is the first page alphabetically.

If you want more control over the naming of the output files you can configure rollup inside the Astro config:

Customising Output Filenames

import { defineConfig } from 'astro/config'

export default defineConfig({
  vite: {
    build: {
      rollupOptions: {
        output: {
          entryFileNames: 'entry.[hash].mjs',
          chunkFileNames: 'chunks/chunk.[hash].mjs',
          assetFileNames: 'assets/asset.[hash][extname]',
        },
      },
    },
  },
})

If you need more control over the importing of your tailwind styles you can disable the default style sheet and import your own:

applyBaseStyles

import { defineConfig } from 'astro/config';

export default defineConfig({
  integrations: [
    tailwind({
      applyBaseStyles: false,
    }),
  ],
});
/* /src/styles/base.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
// /src/pages/index.astro
---
import '../styles/base.css'
---
Princesseuh commented 1 year ago

Closing as a duplicate of https://github.com/withastro/astro/issues/7469

mschoeffmann commented 3 months ago

I just created an integration for this: https://www.npmjs.com/package/astro-generic-build-filenames