Arif Khan
Arif Khan

Reputation: 246

How to import scss file as variable in react with typescript

I am unable to import scss file in below format.

import * as styles from './index.scss';

getting below error :

can not find module './index.scss'

I want to use class name like below :

className={styles.anyClassName}

Upvotes: 16

Views: 32426

Answers (5)

Sayyed Amir Hussain
Sayyed Amir Hussain

Reputation: 1

I solved that issue using Run Powershell as Administrator and execute that code: Set-ExecutionPolicy RemoteSigned Press A And Enter

Refer this if not clear: After npm updating packages .ps1 cannot be loaded because running scripts is disabled on this system

and refer this alsp: No such file or directory

Upvotes: -1

Positonic
Positonic

Reputation: 9411

Be sure you have react-scripts-scss-ts installed.

If not run:

 npm i react-scripts-scss-ts --save

Upvotes: 2

user2668735
user2668735

Reputation: 1205

In order to import SCSS as object in TS like this :

import * as styles from './index.scss';
  • Create file 'global.d.ts' in your source directory (or outside, but must be included in the src directory defined in tsconfig)
  • Add the following code inside
declare module '*.scss' {
  const content: {[className: string]: string};
  export = content;
}

https://basarat.gitbooks.io/typescript/docs/types/ambient/d.ts.html

Upvotes: 32

Ikram Ud Daula
Ikram Ud Daula

Reputation: 1321

One of this way you work with .scss style on your create-react-app project. you need some steps on your projects.

  1. git commit all changes
  2. run yarn run eject from your project command prompt.
  3. Go to the location and open the file config/webpack.config.dev.js approximately line #173. Replace test: /\.css$/, with test: /\.s?css$/,
  4. Go to the location and open the file config/webpack.config.prod.js approximately line #185. Replace test: /\.css$/, with test: /\.s?css$/,
  5. add your .scss file on your component like

    import './App.scss';
    

    and uses like

    <div className="your-styled-class-name">
        <p>Styed Text</p>
    </div>
    

That's it.

Upvotes: -1

jameslafferty
jameslafferty

Reputation: 2182

I came across this question recently, and figured it might be useful to add an answer that helps do this at the time the project is generated (using create-react-app) and without the need to eject or modify the webpack configs:

create-react-app my-app --scripts-version=react-scripts-scss-ts

Upvotes: 3

Related Questions