lightningcss icon indicating copy to clipboard operation
lightningcss copied to clipboard

CSS custom media not working in development mode

Open azat-io opened this issue 3 years ago • 5 comments

I created a demo repo: https://github.com/azat-io/lightningcss-custom-media

Look it up please.

If you run the command pnpm start, @custom-media will not work. But if you build the project with pnpm build, everything will work correctly.

azat-io avatar Jan 19 '23 15:01 azat-io

Unfortunately, the Vite plugin can only process one file at a time so @custom-media defined in a separate file cannot work. Vite would need to switch to using the Lightning CSS bundler in order for us to make this work. Please see https://github.com/vitejs/vite/issues/11029

devongovett avatar Jan 19 '23 16:01 devongovett

@devongovett This code also not works in development mode:

@custom-media --screen-tablet (width >= 860px);

body {
  background: blue
}

@media (--screen-tablet) {
  body {
    background: red;
  }
}

azat-io avatar Jan 19 '23 16:01 azat-io

Seems to work in the playground.

Make sure that you are setting a browserslist though, or nothing will be compiled. Even though no browser supports@custom-media currently, we need to compile only based on targets for forward compatibility.

devongovett avatar Jan 19 '23 16:01 devongovett

@devongovett I set browserslist but nothing changed.

I updated my repo: https://github.com/azat-io/lightningcss-custom-media

Could you try to run this project?

  1. pnpm install
  2. pnpm start

I expect a red screen but it's blue.

azat-io avatar Jan 19 '23 17:01 azat-io

Vite would need to switch to using the Lightning CSS bundler in order for us to make this work. Please see https://github.com/vitejs/vite/issues/11029

Hey @devongovett, the linked work looks done. I'm using lightningcss in an Astro project with vite configured to use lightningcss and @custom-media in other files are still not visible. My astro.config.ts:

  vite: {
    css: {
      transformer: "lightningcss",
      lightningcss: {
        targets: browserslistToTargets(
          browserslist(">= 0.25% and last 1 year and not dead"),
        ),
        drafts: {
          customMedia: true,
        },
      },
    },
    build: {
      cssMinify: "lightningcss",
    },
  },

If I manually @import "../styles/global/custom-media-queries.css"; in the CSS file that uses the media queries, it works.

Would you expect this to work when Vite is set to transform/bundle with lightningcss?

altano avatar Apr 15 '25 09:04 altano