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

Angular 14导入SCSS变量报错:Module parse failed: Unexpected token

Angular 14升级后SCSS调色板:export语法报错问题

错误现象

升级Angular 14后,原SCSS调色板的:export代码块触发解析错误,Angular 13中运行正常。错误日志如下:

Error: Module parse failed: Unexpected token (1:0)
File was processed with these loaders:
 * ./node_modules/resolve-url-loader/index.js
 * ./node_modules/@angular-devkit/build-angular/node_modules/sass-loader/dist/cjs.js
You may need an additional loader to handle the result of these loaders.
> :export {
|   -mainBlue-: "#4285EB";
|   -delete-: "#ff3f3f";

相关代码

1. palette.scss中的:export块

:export {
  -mainBlue-: "#{$main-blue}";
  -delete-: "#{$delete}";
  -orange-: "#{$orange}";
  -white-: "#{$white}";
  -error-: "#{$error}";
}

2. palette.scss.ts的类型定义

export interface Palette {
  mainBlue: string,
  delete: string,
  orange: string,
  white: string,
  error: string,
}

let palette;
export default palette;

3. angular.json的全局样式配置

"styles": [
  "src/styles/styles.scss",
  "src/styles/palette.scss",
]

4. 组件中原有导入处理逻辑

let stringifiedPalette: string = palette
  .replace(/(:export|\n|\s)/g,'')
  .replace(/;/g,',')
  .replace(/-/g,'"');
const lastCommaIndex = stringifiedPalette.lastIndexOf(',');
stringifiedPalette = stringifiedPalette.slice(0, lastCommaIndex) + stringifiedPalette.slice(lastCommaIndex + 1);
this.colorPalette = JSON.parse(stringifiedPalette);

原因分析

Angular 14升级了webpack及样式处理loader链,全局样式(angular.json中styles数组配置的文件)的处理流程不再支持将SCSS的:export块解析为JS模块输出。原Angular 13的loader链允许这种“全局样式+模块导出”的混合用法,现在则会因无法识别:export语法报错。

解决思路

方案1:调整调色板导入方式,移除全局样式配置

  1. 从angular.json的styles数组中移除src/styles/palette.scss,避免作为全局样式处理。
  2. 在需要使用调色板的TS文件中直接导入palette.scss:
    import palette from '../styles/palette.scss';
    this.colorPalette = palette;
    
  3. 确保Angular的sass-loader配置支持SCSS模块导出:在angular.json的build.options中添加"stylePreprocessorOptions",或者通过自定义webpack配置(使用@angular-builders/custom-webpack)开启css-loader的modules选项,确保:export能被解析为JS对象。

方案2:改用TS统一管理颜色变量(推荐)

彻底抛弃:export的跨语言传递方式,用TS文件统一维护颜色变量,同时供SCSS和TS使用:

  1. 创建src/styles/palette.ts,定义并导出颜色常量:
    export const palette = {
      mainBlue: '#4285EB',
      delete: '#ff3f3f',
      orange: '#your-orange-value',
      white: '#ffffff',
      error: '#your-error-value'
    };
    
    export type Palette = typeof palette;
    
  2. 在SCSS中使用这些变量:
    • 方式一:通过脚本将TS变量转化为SCSS变量文件(如palette-vars.scss),然后在SCSS中导入。
    • 方式二:使用sass-loader的自定义importer功能,直接在SCSS中引用TS变量。
  3. 在TS组件中直接导入使用:
    import { palette } from '../styles/palette';
    this.colorPalette = palette;
    

这种方式避免了loader兼容性问题,同时实现TS和SCSS变量的统一维护。

方案3:自定义webpack配置兼容原有写法

如果需要保留原有:export写法,需扩展Angular的webpack配置:

  1. 安装@angular-builders/custom-webpack,替换默认的builder。
  2. 创建webpack.config.js,添加处理SCSS导出的loader规则,确保:export块被正确解析为JS模块。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 03:56:12