You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular项目中使用SCSS配置NG-Zorro失效求助

解决Angular项目中使用SCSS配置NG-Zorro主题无效果的问题

我仔细看了你的配置,核心问题出在webpack规则的路径配置错误,还有一些版本兼容和loader细节需要调整,一步步来解决:

1. 修复Webpack配置中的路径错误

你在webpack.config.js里给scss和less规则设置了include: [path.resolve(__dirname, "not_exist_path")],这个不存在的路径会导致loader完全不处理任何文件,自然主题变量不会生效。修改如下:

  • 对于SCSS规则:指定include为项目源码目录src,确保项目内的SCSS文件能被处理
  • 对于LESS规则:需要加入node_modules/ng-zorro-antd路径,这样才能处理NG-Zorro自带的LESS文件
  • 给less-loader添加javascriptEnabled: true配置——这是NG-ZORRO的LESS文件必须的设置

修改后的webpack.config.js:

const path = require("path");
const AntdScssThemePlugin = require("antd-scss-theme-plugin");
const config = {
  module: {
    rules: [
      {
        test: /\.scss$/,
        include: [path.resolve(__dirname, "src")],
        exclude: /node_modules/,
        use: [
          { loader: "style-loader" },
          { loader: "css-loader" },
          AntdScssThemePlugin.themify({
            loader: "sass-loader",
            options: {
              sourceMap: process.env.NODE_ENV !== 'production',
            },
          }),
        ],
      },
      {
        test: /\.less$/,
        include: [
          path.resolve(__dirname, "src"),
          path.resolve(__dirname, "node_modules/ng-zorro-antd")
        ],
        use: [
          {
            loader: 'style-loader',
            options: {
              sourceMap: process.env.NODE_ENV !== 'production',
            },
          },
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1,
              sourceMap: process.env.NODE_ENV !== 'production',
            },
          },
          AntdScssThemePlugin.themify({
            loader: 'less-loader',
            options: {
              lessOptions: {
                javascriptEnabled: true
              }
            }
          }),
        ],
      },
    ],
  },
  plugins: [
    new AntdScssThemePlugin(path.resolve(__dirname, 'src', 'assets/theme.scss')),
  ],
  watchOptions: {
    ignored: /dist/,
  },
};
module.exports = config;

2. 修复版本兼容性问题

你的Angular版本是10.x,但NG-Zorro用的是9.3.0,跨大版本的依赖很容易导致奇怪的兼容问题。建议把NG-Zorro升级到对应Angular 10的版本:

修改package.json中的ng-zorro-antd版本:

"dependencies": {
  // ...其他依赖
  "ng-zorro-antd": "^10.2.0",
  // ...其他依赖
}

另外,你使用的sass-loader@7.0.1版本太旧,和Angular 10的webpack版本不兼容,建议升级到sass-loader@9.0.3(这个版本和Angular 10适配)。

3. 验证并重启项目

完成上述修改后:

  1. 执行npm install更新依赖
  2. 停止当前的ng serve,重新执行ng serve启动项目

此时你的theme.scss中的$primary-color: red;应该会生效,NG-Zorro的组件主色调会变成红色。

内容的提问来源于stack exchange,提问作者dm0312

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 17:13:12