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

Angular Cypress组件测试引入Tailwind CSS遇加载器错误求助

解决Angular Cypress组件测试中Tailwind CSS引入问题

错误原因

出现Module parse failed: Unexpected character '@'错误,是因为Cypress组件测试的Webpack配置未配置PostCSS loader,无法解析Tailwind的@tailwind这类指令。

解决步骤

1. 安装必要依赖

确保项目已安装Tailwind及PostCSS相关工具:

npm install tailwindcss postcss autoprefixer --save-dev

2. 配置Cypress专属Webpack规则

在项目根目录创建cypress/webpack.config.js,添加以下配置:

const { AngularWebpackPlugin } = require('@ngtools/webpack');
const postcssLoader = {
  loader: 'postcss-loader',
  options: {
    postcssOptions: {
      plugins: [
        require('tailwindcss'),
        require('autoprefixer'),
      ],
    },
  },
};

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        exclude: /node_modules/,
        use: ['style-loader', 'css-loader', postcssLoader],
      },
      {
        test: /\.css$/,
        include: /node_modules/,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.(ts|js)$/,
        loader: '@ngtools/webpack',
      },
    ],
  },
  plugins: [new AngularWebpackPlugin({ tsconfig: './tsconfig.json' })],
  resolve: { extensions: ['.ts', '.js'] },
};

3. 关联Webpack配置到Cypress

修改cypress.config.ts,指定组件测试使用上述Webpack配置:

import { defineConfig } from 'cypress';

export default defineConfig({
  component: {
    devServer: {
      framework: 'angular',
      bundler: 'webpack',
      webpackConfig: require('./cypress/webpack.config.js'),
    },
  },
});

4. 导入Tailwind样式文件

在cypress/support/component.ts中导入项目的Tailwind主样式文件(假设你的样式文件在src/styles.css,且已配置@tailwind base;等指令):

import '../../src/styles.css';

验证

重新启动Cypress组件测试,样式即可正常加载,解析错误会消失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 00:52:05