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

Next.js项目无法加载antd less样式,提示文件未找到如何解决?

问题原因
  1. Less文件中使用的~前缀是Webpack生态约定的node_modules目录指代符,Next.js默认的Less解析规则未适配该约定,解析时将~识别为普通路径字符,因此会从当前目录、项目根目录等位置搜索~antd开头的路径,无法匹配到node_modules下的antd依赖。
  2. 你使用了@styles路径别名,若未在项目配置中声明别名映射,也会导致样式文件引入失败。
解决方案
  • 第一步:安装必要依赖
    首先安装Less和Less编译工具:
    npm install less less-loader -D
    # 若使用pnpm
    pnpm add less less-loader -D
    # 若使用yarn
    yarn add less less-loader -D
    
  • 第二步:修改next.config.js配置
    新增Webpack别名规则和Less编译配置,示例如下:
    const path = require('path');
    
    /** @type {import('next').NextConfig} */
    const nextConfig = {
      webpack: (config) => {
        // 适配~前缀,指向node_modules目录
        config.resolve.alias['~'] = path.resolve(__dirname, 'node_modules');
        // 配置@styles别名,对应你的样式目录
        config.resolve.alias['@styles'] = path.resolve(__dirname, 'app/styles');
        return config;
      },
      lessLoaderOptions: {
        lessOptions: {
          javascriptEnabled: true, // Antd样式编译必须开启该配置
        },
      },
    }
    
    module.exports = nextConfig;
    
    如果你使用的是低于13版本的Next.js,也可以安装next-with-less插件简化配置,不需要手动写LessLoader相关规则。
  • 第三步:补充TS路径别名配置(TS项目必做)
    在tsconfig.json的compilerOptions字段下新增路径映射,避免TS类型报错:
    {
      "compilerOptions": {
        "paths": {
          "@styles/*": ["./app/styles/*"]
        }
      }
    }
    
  • 第四步:可选简化方案
    你也可以直接修改antdstyles.less中的导入语句,去掉~前缀,Next.js默认会优先从node_modules目录查找依赖,修改后内容如下:
    @import 'antd/dist/antd.less';
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 21:48:01