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

升级Angular至15搭配@angular-builders/custom-webpack遇style-loader找不到错误

Angular 12升级到15后构建报错:无法找到style-loader

问题背景

将Angular项目从12版本升级至15版本后,使用自定义webpack配置(结合single-spa-angular)执行构建时,出现以下错误:

Error: Module not found: Error: Can't resolve 'style-loader' in 'my-project-path'

项目相关配置如下:

angular.json中的build配置

"architect": {
    "build": {
        "builder": "@angular-builders/custom-webpack:browser",
        "options": {
            "customWebpackConfig": {
                "path": "config/library.webpack-config.js",
                "libraryName": "overview",
                "libraryTarget": "system"
            }
        }
    }
}

config/library.webpack-config.js内容

/* eslint-disable no-undef,filenames/match-regex */
const singleSpaAngularWebpack = require('single-spa-angular/lib/webpack').default;
const {WebpackManifestPlugin} = require('webpack-manifest-plugin');
/* eslint-enable no-undef,filenames/match-regex */

const CLIENT_CORE_SERVICES = 'clientCoreServices';

// eslint-disable-next-line no-undef
module.exports = (config, options) => {
  config.plugins.push(new WebpackManifestPlugin(options));

  const singleSpaWebpackConfig = singleSpaAngularWebpack(config, options);
  const externals = singleSpaWebpackConfig.externals || [];

  externals.push(CLIENT_CORE_SERVICES);

  const mergedConfig = {
    ...singleSpaWebpackConfig,
    externals
  };

  return mergedConfig;
};

解决方法

1. 升级single-spa-angular至兼容Angular 15的版本

Angular 14及以上版本默认使用mini-css-extract-plugin处理样式,不再依赖style-loader,而旧版single-spa-angular可能仍在引用style-loader导致报错。执行以下命令升级依赖:

npm install single-spa-angular@latest --save-dev

2. 调整webpack配置(若升级后仍有问题)

检查single-spa-angular生成的webpack配置,确认样式处理规则适配Angular 15。可以在自定义webpack配置中手动覆盖样式loader配置:

module.exports = (config, options) => {
  // 原有代码...

  // 替换样式loader规则
  config.module.rules.forEach(rule => {
    if (rule.test.toString().includes('css') || rule.test.toString().includes('scss')) {
      // 移除style-loader
      rule.use = rule.use.filter(loader => !loader.loader.includes('style-loader'));
      // 添加mini-css-extract-plugin的loader
      rule.use.unshift(require('mini-css-extract-plugin').loader);
    }
  });

  // 注册mini-css-extract-plugin插件
  config.plugins.push(new require('mini-css-extract-plugin')());

  return mergedConfig;
};

3. 临时安装style-loader(不推荐)

如果暂时无法升级single-spa-angular,可以手动安装兼容版本的style-loader作为过渡:

npm install style-loader@^3.3.3 --save-dev

注意:此方案可能引发样式处理冲突,仅作临时过渡使用,优先推荐升级single-spa-angular。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 03:57:36