【问题标题】:How to import scss file as variable in react with typescript如何将scss文件作为变量导入与打字稿反应
【发布时间】:2018-12-04 22:01:10
【问题描述】:

我无法导入以下格式的 scss 文件。

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

低于error

找不到模块'./index.scss'

我想使用如下类名:

className={styles.anyClassName}

【问题讨论】:

标签: reactjs


【解决方案1】:

为了像这样在 TS 中将 SCSS 作为对象导入:

import * as styles from './index.scss';
  • 在您的源目录(或外部,但必须包含在 tsconfig 中定义的 src 目录中)创建文件“global.d.ts”
  • 在里面添加如下代码
declare module '*.scss' {
  const content: {[className: string]: string};
  export = content;
}

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      确保您已安装 react-scripts-scss-ts

      如果不运行:

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

      【讨论】:

        【解决方案4】:

        其中一种方式是在 create-react-app 项目中使用 .scss 样式。您的项目需要一些步骤。

        1. git 提交所有更改
        2. 在您的项目命令提示符下运行 yarn run eject
        3. 转到该位置并打开文件config/webpack.config.dev.js 大约在第 #173 行。将test: /\.css$/, 替换为test: /\.s?css$/,
        4. 转到该位置并打开文件config/webpack.config.prod.js 大约在第 185 行。将test: /\.css$/, 替换为test: /\.s?css$/,
        5. 在你的组件上添加你的.scss文件

          import './App.scss';
          

          并使用类似

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

        就是这样。

        【讨论】:

        • 您好,我想从 'xyz.css' 导入为 import * 作为样式。那是行不通的。
        • 如果使用create-react-app 命令然后按照这个答案。 stackoverflow.com/questions/49856468/…
        • 是的,我正在使用带有 typescript 的 create-react-project。上述方法也行不通。请查看 git repo:github.com/mdarif-k/React-Typescript1.git
        • 嗨。我已经更新了我的答案。这次您创建一个新项目,然后尝试这种方式。我已经检查过了。
        • 弹出应用程序似乎应该是最后的解决方案,因为它引入了一堆配置和基础设施,这些配置和基础设施可能最好留在你的代码库中。灵活性可以很好,但清晰度通常更好,配置 webpack 可能会变成一个相当深的兔子洞。只是我的两分钱。
        【解决方案5】:

        我使用以管理员身份运行 Powershell 解决了该问题并执行该代码: Set-ExecutionPolicy RemoteSigned 按 A 并输入

        如果不清楚,请参考: After npm updating packages .ps1 cannot be loaded because running scripts is disabled on this system

        并参考这个alsp: No such file or directory

        【讨论】:

          猜你喜欢
          • 2023-04-10
          • 2021-01-20
          • 2020-04-02
          • 1970-01-01
          • 2019-08-29
          • 2017-11-27
          • 1970-01-01
          • 2017-01-16
          • 2017-03-31
          相关资源
          最近更新 更多