How to split media queries under webpack config?
Asked Answered
S

2

17

since we can import style sheets like below :

<link rel="stylesheet" media="screen and (min-width: 900px)" href="widescreen.css">
<link rel="stylesheet" media="screen and (max-width: 600px)" href="smallscreen.css">

and this will help faster loading of web site by loading only a css file which meets media attribute conditions.MDN

I had no luck searching for webpack config that can split queries or at least let me manually specify which css entry should load on which media.

my only solution was to write nodejs script and inject index.html at build time but that's not clean way to do it in my opinion.

so is there any webpack config for this kind of stuff?

Sector answered 1/1, 2019 at 14:6 Comment(2)
I take it you want webpack to separate your styles into 2 css files for you, right?Sinistrorse
i prefer that webpack separate css by how many different media queries exist and import them as link tag on header of html fileSector
F
8

This is more like a comment, but I believe there is a plugin for that:

https://github.com/SassNinja/media-query-plugin

Have you ever thought about extracting your media queries from your CSS so a mobile user doesn't have to load desktop specific CSS? If so this plugin is what you need!

Feverroot answered 7/1, 2019 at 19:25 Comment(3)
As i far as i understand i should sperate my css files with media queries manually with naming convention. Thats not exactly what I'm looking for also it use dynamic import for importing css which i rather not use. But this can make life a little bit easier.Sector
There also is a PostCss counterpart from the same author: github.com/SassNinja/postcss-extract-media-query. I guess he/she likes them media queriesFeverroot
Deffenetly he/she into media queries. Whats your thinking about dynamic imports. I much rather use link tag. Actually i came across this plugin before but i will have to add link tag manually on my index.html file i will try and see if it actually work this way.Sector
R
0

Without doing dynamic imports you're limited to what Webpack can do as a static module bundler at compile time. Because the behavior you're looking to get is required at runtime, Webpack cannot infer anything but what you have already told it about the environment.

Having said that, you can create multiple build outputs that are each configured for a particular platform. Assuming the only difference in your code base is your CSS, everything but your output CSS should be identical across each build configuration. Going this route means setting up multiple routes, one for each media type, and serving the files from that configuration.

It's definitely more work than going down the dynamic imports path, but it's doable and completely segregates your application by media type.

Rizzo answered 12/1, 2019 at 14:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.