Angular 13升级至15后无法解析@angular/cdk/overlay-prebuilt.css报错
问题
迁移后构建时报错:
./node_modules/@app/app-core/theme/app-theme.scss - Error: Module build failed (from ./node_modules/css-loader/dist/cjs.js):
Error: Can't resolve 'node_modules/@angular/cdk/overlay-prebuilt.css' in '/Users/user/node_modules/@app/app-core/theme'
相关配置及代码片段:
- angular.json中的styles与assets配置:
"assets": [ "src/assets", { "glob": "**", "input": "node_modules/@app/app-core/theme", "output": "app-core" } ], "styles": [ "node_modules/@app/app-core/theme/app-theme.scss", "src/styles.sass" ],
- app-theme.scss中的关键导入语句:
@import 'node_modules/@angular/cdk/overlay-prebuilt.css';
手动将该导入改为@import '~@angular/cdk/overlay-prebuilt.css';可正常运行,但无法修改app-theme.scss源文件,且已尝试删除node_modules和package-lock.json重装依赖,无效。
原因
Angular 15配套的css-loader v6+版本,移除了对node_modules/相对路径解析的支持,同时不再默认识别~前缀(旧版本Angular的webpack会自动将~映射到node_modules根目录)。原导入语句试图从@app/app-core/theme目录下查找node_modules,显然该路径不存在,导致解析失败。
解决方案
方案1:自定义webpack别名(推荐)
通过配置webpack别名,让css-loader直接定位到CDK包:
- 安装自定义webpack构建器:
npm install @angular-builders/custom-webpack --save-dev
- 在项目根目录新建
webpack.config.js文件:
module.exports = { resolve: { alias: { '@angular/cdk': require.resolve('@angular/cdk') } } };
- 修改angular.json中的构建配置,替换builder并引入自定义配置:
"architect": { "build": { "builder": "@angular-builders/custom-webpack:browser", "options": { "customWebpackConfig": { "path": "./webpack.config.js" }, // 保留原有其他配置项 } }, "serve": { "builder": "@angular-builders/custom-webpack:dev-server", // 保留原有其他配置项 } }
方案2:用patch-package给依赖包打补丁
如果允许对依赖包做临时修改,可通过patch-package实现补丁自动应用:
- 安装依赖工具:
npm install patch-package --save-dev
- 手动修改
node_modules/@app/app-core/theme/app-theme.scss中的导入语句为@import '~@angular/cdk/overlay-prebuilt.css'; - 生成补丁文件:
npx patch-package @app/app-core
- 在package.json的scripts中添加自动补丁脚本:
"scripts": { "postinstall": "patch-package" }
后续每次执行npm install时,补丁会自动应用到依赖包中。
内容的提问来源于stack exchange,提问作者user12302787

