Anthony Kong
Anthony Kong

Reputation: 40624

How to enable `import styles from './local.css' ` syntax in a create-react-app project?

I used npx create-react-app myapp --typescript to create a skeleton project.

My perfer css import styles is import styles from './App.css such that I can do something like this

<div className={styles.container}>Hello</div>

However if i tried this style I will get an error

Type error: Cannot find module './App.css'.  TS2307

    2 | import logo from './logo.svg';
    3 |
  > 4 | import styles from './App.css';

How can configure my react-app to accept this coding style?

create-react-app version is 2.1.3

Upvotes: 1

Views: 389

Answers (2)

Sttatusx
Sttatusx

Reputation: 36

  1. change 'App.css' to 'App.module.css'

  2. import it import styles from './App.module.css'

  3. use the classes like this

<div className={styles.app}>Hello World!</div>

Reference Link

Upvotes: 1

dabishan
dabishan

Reputation: 691

You cannot import stylesheets the way you did as it is not a js module. You can do this:

import './App.css'

You will only be able to do the way you did it if you created styles as js objects and only apply to style attribute not className. Example:

On Style.js not css

const styles =  {
    container: {
        background: red,
        fontSize: '15px'
    }
}

export default styles;

On App.js

import styles from './styles'

and on your render()

<div style={styles.container}>Your Content</div>

Note its style not class

If you are using typed-css-modules, you will have to run tcm --watch alongside or tcm by itself. Once you do it, tslint won't give you any errors unless it cannot find the styles.

Upvotes: 0

Related Questions