简体   繁体   English

如何导入 scss 文件作为变量与打字稿反应

[英]How to import scss file as variable in react with typescript

I am unable to import scss file in below format.我无法导入以下格式的 scss 文件。

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

getting below error :得到以下error

can not find module './index.scss'找不到模块'./index.scss'

I want to use class name like below :我想使用如下类名:

className={styles.anyClassName}

In order to import SCSS as object in TS like this :为了像这样将 SCSS 作为 TS 中的对象导入:

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)在源目录(或外部,但必须包含在 tsconfig 中定义的 src 目录中)创建文件“global.d.ts”
  • 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 https://basarat.gitbooks.io/typescript/docs/types/ambient/d.ts.html

我最近遇到了这个问题,并认为添加一个有助于在生成项目时执行此操作的答案(使用 create-react-app)并且无需弹出或修改 webpack 配置可能会很有用:

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

Be sure you have react-scripts-scss-ts installed.确保你安装了react-scripts-scss-ts

If not run:如果没有运行:

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

One of this way you work with .scss style on your create-react-app project.create-react-app项目中使用.scss样式的方式之一。 you need some steps on your projects.你的项目需要一些步骤。

  1. git commit all changes git 提交所有更改
  2. run yarn run eject from your project command prompt.从您的项目命令提示符运行yarn run eject
  3. Go to the location and open the file config/webpack.config.dev.js approximately line #173.转到该位置并打开文件config/webpack.config.dev.js大约第 173 行。 Replace test: /\\.css$/, with test: /\\.s?css$/,test: /\\.css$/,替换为test: /\\.css$/, test: /\\.s?css$/,
  4. Go to the location and open the file config/webpack.config.prod.js approximately line #185.转到该位置并打开文件config/webpack.config.prod.js大约第 185 行。 Replace test: /\\.css$/, with test: /\\.s?css$/,test: /\\.css$/,替换为test: /\\.css$/, test: /\\.s?css$/,
  5. add your .scss file on your component like在您的组件上添加您的.scss文件,例如

    import './App.scss';

    and uses like并使用像

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

That's it.就是这样。

I solved that issue using Run Powershell as Administrator and execute that code: Set-ExecutionPolicy RemoteSigned Press A And Enter我使用以管理员身份运行 Powershell 解决了该问题并执行该代码: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如果不清楚,请参考: 在 npm 更新包之后,无法加载 .ps1 因为在此系统上禁用了运行脚本

and refer this alsp: No such file or directory并参考这个 alsp: 没有这样的文件或目录

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM