Skip to content

Be able to use styleName or style tag inside jsx or tsx for scoped css #107

@gabalicious

Description

@gabalicious

Description

So the problem with using traditional react css module pattern is that you end up writing react components like below example and this is not a great developer experience in my opinion.

  1. React css modules use className with brackets rather than a string.
  2. One has to manually import styles for every component.
import styles from './App.module.css'
function App() {
  return (
 <div className={styles.a}>
    <h1 className={styles.b}>123</h1>
  </div>
  )
}
  
export default App

Suggested solution

As a developer using react and vite I really wish that I could write something like this.

// App.jsx

<div styleName="a"></div>;
/* App.module.css */

a {
  color: red;
}

Vite w/ react plugin would automatically compile like this and import by naming convention (example.jsx will import example.module.css if found.)

import '/.App.module.css'
/*
.a__hash {
  color: red;
}
 */

function App() {

  return (
    <div className ="a__hash">

    </div>
  )
}

Alternative

Alternatively, I wish I could do something like this

function App() {

  return (
    <div styleName="a">

    </div>
  )
}

export default App

<style>
  .a{
    color: red
  }
</style>

And that it would compile to the same as first example.

import '/.App.module.css'
/*
.a__hash {
  color: red;
}
 */

function App() {

  return (
    <div className="a__hash">

    </div>
  )
}

Additional context

Vue and Angular have a pretty good developer experience when it comes to scoped css and I think if this was implemented with vite using one or both of the methods above, it would be awesome. The packages below were/are packages that seem to implement this but I wasn't sure if it was possible to make it work with vite.

https://github.com/gajus/babel-plugin-react-css-modules
https://github.com/gajus/react-css-modules

I tried doing something like below in vite 4 config, many different ways but no luck. Maybe someone else will have better luck.

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [
    react({
      babel: {
          plugins: ["babel-plugin-react-css-modules"],
      },
    }),
  ],
})

Validations

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions