parcel-bundler / parcel

The zero configuration build tool for the web. πŸ“¦πŸš€
https://parceljs.org
MIT License
43.46k stars 2.27k forks source link

Correct process for using CSS Modules in HTML #3046

Open DanProudfoot opened 5 years ago

DanProudfoot commented 5 years ago

❔ Question

Hi. I feel like I've been trying to find some sort of process for this all day.

I want to use parcel to build a nice simple flat html page - the project doesn't really need React or anything, i'm just trying out to see if I can do a project using Parcel rather than the whole gulp routine.

So, right now I've turned on modules: true in .postcssrc and started looking into posthtml. Thing is...posthtml looks pretty dead. Both of the plugins for posthtml that seem to do integration with modules are multiple years old and don't seem to integrate with parcel's system of putting the classname mappings in a file with an unknowable filename.

πŸ”¦ Context

I feel like I'm missing something with my approach to css modules. I can directly see the benefit in React, and want to get that same level of usefulness in plain HTML (or, slightly enhanced HTML).

Am i barking up the wrong tree?

🌍 Your Environment

Software Version(s)
Parcel 1.12.3
Node 11.10.0
npm/Yarn Yarn 1.13.0
Operating System Windows 10 x64
mischnic commented 5 years ago

So having "constant" file names for the css file would help?

Or is there a bigger problem with some posthtml-postcss intergration?

DanProudfoot commented 5 years ago

Hi thanks for getting back.

I wrote this issue at a moment of semi-desperation, and sort of moved on and just used BEM for my CSS after that passed.

Now I've thought more about it, I think I was looking at it the wrong way.

If we look at this posthtml-css-modules plugin, it says it wants the JSON css module representation, which I think Parcel inlines into the .js bundle. If that JSON file(s) was stored in some temporary location that could be referenced in the .posthtmlrc file that would potentially solve this.

mischnic commented 5 years ago

Ah, I see. We would indeed need to export the CSS modules json into a file.

The example given for webpack uses the template-system of the webpack html-loader

<form class="${require('./Form.css').form}">
    <input type="text">
    <button class="${require('./Form.css').submitButton}">Submit</button>
</form>

https://github.com/maltsev/css-modules-webpack-example/blob/master/src/Form.html

DanProudfoot commented 5 years ago

Oh boy, that isn't exactly pleasant is it?

mischnic commented 5 years ago

Oh boy, that isn't exactly pleasant is it?

πŸ˜„ We're definitely not doing this kind of JS templating ourselves any time soon.

DanProudfoot commented 5 years ago

Thank goodness :rofl

I think the posthtml plugin lets you use section.block notation or whatever, so if css module classnames are scoped per file we shouldn't have to worry about anything equivalent to the above Webpack templating.