为什么在 sass 中使用 `@use` 而不是 `@import` 在 create-react-app 中不起作用?

问题描述 投票:0回答:1

我已经在 React 中开发一个网站几天了,我想我应该使用 Sass,但由于某种原因,使用

@use
不起作用,而使用 已弃用的
@import
却可以。

这是我的package.json:

{
    "name": "a-cool-project-name",
    "version": "0.1.0",
    "private": true,
    "scripts": {
        "start": "react-scripts start",
        "build": "react-scripts build",
        "eject": "react-scripts eject"
    },
    "eslintConfig": {
        "extends": [
            "react-app",
            "react-app/jest"
        ]
    },
    "browserslist": {
        "production": [
            ">0.2%",
            "not dead",
            "not op_mini all"
        ],
        "development": [
            "last 1 chrome version",
            "last 1 firefox version",
            "last 1 safari version"
        ]
    },
    "devDependencies": {
        "@babel/plugin-proposal-private-property-in-object": "^7.21.11"
    },
    "dependencies": {
        "@fortawesome/fontawesome-svg-core": "^6.5.1",
        "@fortawesome/free-solid-svg-icons": "^6.5.1",
        "@fortawesome/react-fontawesome": "^0.2.0",
        "react": "^18.2.0",
        "react-dom": "^18.2.0",
        "react-router-dom": "^6.22.0",
        "react-scripts": "5.0.1",
        "sass": "^1.70.0",
        "web-vitals": "^2.1.4"
    }
}

正如你所看到的,我已经将 sass 更新到最新版本,并且正在使用react-scripts

v5.1.0
,这应该足以使用
@use
关键字。

这是我要使用的

_variables.scss
文件:

$background-color: #313131;
$main-color: #666666;
$accent-color: #65c8fb;

这是我要在其中导入变量文件的

Home.scss
文件:

@use '../variables';

.home-page {
    .img-header {
        position: relative;
        width: 100%;

        img {
            width: 100%;
        }

        .objective {
            position: absolute;
            bottom: -5em;
            left: 10%;
            width: 50%;
            padding: 5em;
            background: $main-color;
            border-radius: 1em;
        }
    }
}

这一切结合起来给了我以下错误:

Failed to compile.

SassError: Undefined variable.
   ╷
18 │             background: $main-color;
   │                         ^^^^^^^^^^^
   ╵
  src\style\pages\Home.scss 18:25  root stylesheet

@use '../variables';
替换
@import '../variables'
效果很好,但我不想使用已弃用的东西。

有人知道我可以做什么来解决这个问题吗?
预先感谢!

reactjs sass create-react-app dart-sass
1个回答
0
投票

当从

@use
访问变量或混合时,您需要通过其名称空间来访问它,默认情况下,该名称空间是 url 的末尾。

所以,对于你的例子,我相信会是:

@use '../variables';

.home-page {
    .img-header {
        position: relative;
        width: 100%;

        img {
            width: 100%;
        }

        .objective {
            position: absolute;
            bottom: -5em;
            left: 10%;
            width: 50%;
            padding: 5em;
            background: variables.$main-color;
            border-radius: 1em;
        }
    }
}

Sass:@use

© www.soinside.com 2019 - 2024. All rights reserved.