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

使用tsconfig paths导入Less文件时npm run test报错问题

问题与解决方法

问题背景

在tsconfig.json中配置了TypeScript路径映射:

"paths": {     
  "themes/*": [
    "assets/themes/*"
  ]
}

在projects\myplugin\src\lib\modules\home\components\detail.component.less中使用Less导入:

@import 'themes/theme.less';

该导入在构建、发布阶段正常,但执行npm run test时触发解析错误:

@import 'themes/theme.less';
^
Less resolver error:
Webpack resolver error details:
resolve 'themes/theme.less'

问题原因

tsconfig.json的paths仅对TypeScript编译流程生效,测试环境(如Jest、测试用Webpack)不会自动读取该配置,Less解析器也无法直接识别TypeScript的路径映射规则,导致测试时无法定位到目标文件。

解决方案

1. 配置测试环境Webpack的路径别名

如果测试基于Webpack,在测试专用的Webpack配置文件(如webpack.test.js)中添加resolve.alias:

const path = require('path');

module.exports = {
  // 其他配置...
  resolve: {
    alias: {
      'themes': path.resolve(__dirname, 'assets/themes')
    }
  }
};

2. 配置Jest的模块映射(若使用Jest测试)

在jest.config.js中通过moduleNameMapper映射路径,同时处理Less文件的转换:

module.exports = {
  // 其他配置...
  moduleNameMapper: {
    '^themes/(.*)$': '<rootDir>/assets/themes/$1'
  },
  transform: {
    '\\.(less|css)$': 'jest-transform-stub'
  }
};

jest-transform-stub用于忽略Less文件的样式解析,仅保证模块能被正常识别,需提前安装:

npm install jest-transform-stub --save-dev

3. 临时应急:使用相对路径替换别名

将Less导入改为相对路径(不推荐长期使用,路径层级变更时易失效):

@import '../../../../../../assets/themes/theme.less';

4. 使用Less别名插件

安装less-plugin-alias插件:

npm install less-plugin-alias --save-dev

创建Less配置文件(如less.config.js)并添加别名映射:

const LessPluginAlias = require('less-plugin-alias');

module.exports = {
  plugins: [
    new LessPluginAlias({
      paths: {
        'themes': './assets/themes'
      }
    })
  ]
};

确保测试环境加载该Less配置文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 14:52:25