Preact CLI CSS Modules
Asked Answered
M

2

5

The Preact CLI claims it supports CSS Modules out of the box. So this is what I tried; Given 2 files index.js and index.module.scss in the same folder I tried this:

index.js

import { h, Component } from 'preact';
import styles from './index.module.scss';

export default class Layout extends Component {

  render() {
    console.log(styles);
    return (
      <div className={styles.container}>
        {this.props.children}
      </div>
    );
  }
}

index.module.scss

.container {
  margin: 50px auto;
  max-width: 960px;
  width: 100%;
}

The console.log statement prints {}, the class attribute in the HTML is empty.

What am I doing wrong?

Oh, to install this stuff I just did

preact create default my-project
yarn add -D node-sass sass-loader
Maxfield answered 5/3, 2018 at 19:37 Comment(2)
can you try importing styles from a css files instead? import styles from './index.module.css';Prosciutto
Thanks, I just tried this with a fresh setup and CSS files but it did not workMaxfield
M
10

I think I found the issue. preact cli forces you to put your components in the src/components folder or css modules won't work. Now it does.

For completion, it's possible to make CSS Modules work outside the /components folder: https://github.com/developit/preact-cli/issues/522#issuecomment-370835370

Maxfield answered 6/3, 2018 at 15:14 Comment(2)
I am stuck with the same problem, except i NEED css modules to work when importing from outside of /components directory, because i am importing from node_modules/ How can i achieve that?Fairway
@DanilaAlpatov it's possible: github.com/developit/preact-cli/issues/…Maxfield
A
3

@Lukas i voted your answer up caused it's true, but the actually way i believe preact-cli wants us to use it is by adding all reusable styles into style/index.css file. That is added to the index.html in the build and use can reference your style with normal css reference <Comp style='my-style' ....

Aubergine answered 30/7, 2018 at 0:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.