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

使用Modern Sass Compiler时,如何替换Vite配置中的includePaths?

问题

将项目迁移至新的Modern Sass Compiler时,发现Vite并未传递includePaths参数。原配置如下:

{
  css: {
    preprocessorOptions: {
      scss: {
        api: 'modern-compiler',
        includePaths: [ // 需要替换该配置
          path.resolve("views"),
          path.resolve("views/scss/theme"),
        ],
      },
    },
  },
}

构建时出现以下错误:

[sass] Can't find stylesheet to import.
@import "views/scss/front/product/common";
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

尝试使用importers配置但未触发相关方法,配置如下:

{
  css: {
    preprocessorOptions: {
      scss: {
        api: 'modern-compiler',
        importers: [
          {
            findFileUrl(url) {
              console.log(url); // 未打印日志,说明未调用该方法
              // if (!url.startsWith('~')) return null;
              // return new URL(url.substring(1), pathToFileURL('node_modules'));
            }
          }
        ]
      },
    },
  }
}

请问在Sass配置中添加include路径的正确方式是什么?

解决方案

Modern Sass Compiler(Dart Sass现代API)已废弃includePaths,改用loadPaths作为路径配置项,Vite的SCSS预处理器选项可直接传递该参数:

  • 替换原includePaths为loadPaths,正确配置示例:
const path = require('path');

module.exports = {
  css: {
    preprocessorOptions: {
      scss: {
        api: 'modern-compiler',
        loadPaths: [
          path.resolve(__dirname, "views"),
          path.resolve(__dirname, "views/scss/theme"),
        ],
      },
    },
  },
};
  • 关于importers未触发的问题:
    你的importers配置存在格式问题,现代Sass API要求导入器对象的findFileUrl方法需返回URL对象或null,且仅当Sass默认路径逻辑无法匹配时才会触发。若仅需解决路径导入问题,loadPaths已足够;若需自定义导入逻辑,正确示例如下:
const path = require('path');
const { pathToFileURL } = require('url');

module.exports = {
  css: {
    preprocessorOptions: {
      scss: {
        api: 'modern-compiler',
        importers: [
          {
            findFileUrl(url) {
              // 示例:处理带@views前缀的路径
              if (url.startsWith('@views/')) {
                const filePath = path.resolve(__dirname, url.replace('@views/', 'views/'));
                return pathToFileURL(filePath);
              }
              // 返回null让Sass继续使用默认逻辑
              return null;
            }
          }
        ],
      },
    },
  },
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 06:45:01