可以使用 Next.js 在 SASS 中使用绝对导入

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

根本无法在 scss 文件中使用 @/ 导入。

我的变量位于 src/styles/_variables.scss

tsconfig.json:

{
  "compilerOptions": {
    "lib": ["dom", "dom.iterable", "esnext"],
    "baseUrl": ".",
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "paths": {
      "@/*": ["./src/*"],
      "@/styles/*": ["styles/*"],
      "@/components/*": ["components/*"]
    }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
  "exclude": ["node_modules"]
}

next.config.mjs:

/** @type {import('next').NextConfig} */
const nextConfig = {
  sassOptions: {
    includePaths: [path.join(__dirname, "styles/")],
  },
};

export default nextConfig;

我做错了什么?我一生都无法弄清楚这个问题

据我所知,这几乎是在 .scss 文件中使用绝对导入所需要做的一切。

typescript next.js sass
2个回答
0
投票

这比看起来更简单,您只需在

_varaibles.scss
文件中定义所需的变量,例如:

$black: #000;
$white: #fff;
$gray: #f5f5f5;
$pink: #ff69b4;

然后导入你想要的.scss文件中的_varaibles,记得用相对路径导入,例如如果你的

_varaibales
文件位于
src/styles/
你必须导入完整的相对路径,它看起来像这样:
@import "src/styles/_varaibles.scss";
。 然后只需使用文件中的变量即可。

示例:

@import "src/styles/_varaibles.scss";

.main_example_class {
   background-color: $pink;
}

希望对你有帮助,我使用的next,js版本是

14.1.2
,sass版本是
^1.72.0

如果您还有其他问题,请给我留言,我很乐意为您提供帮助。

PS:无需在

next.config.mjs
文件中进行额外配置。


0
投票

假设您有一个名为 _variables.scss 的 Sass 文件,其中包含变量:

// _variables.scss

$primary-color: #007bff;
$secondary-color: #6c757d;
$font-family: 'Arial', sans-serif;

并且您想将这些变量导入到另一个 Sass 文件中,例如 styles.scss:

// styles.scss

@use 'variables';

body {
  font-family: variables.$font-family;
  background-color: variables.$primary-color;
}

h1 {
  color: variables.$secondary-color;
}

确保两个文件(_variables.scss 和 styles.scss)位于同一目录中,或者 @use 指令中指定的路径正确。

我们使用@use指令导入_variables.scss文件。

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