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

配置Vite绝对导入路径时出现stylelint错误求助

Vite项目启动时stylelint动态导入错误解决

问题描述

按照《React 企业级开发之路》2.2.7章节配置Vite项目的绝对导入,运行pnpm run dev或npm run dev启动开发服务器时,出现stylelint相关错误,导致服务启动失败。

错误日志

error when starting dev server:
Error: Dynamic require of "stylelint" is not supported
    at formatError (file:///Users/casey/Dev/react-the-road-to-enterprise/node_modules/.pnpm/vite@3.2.4_ajklay5k626t46b6fyghkbup3i/node_modules/vite/dist/node/chunks/dep-67e7f8ab.js:39975:46)
    at Context.error (file:///Users/casey/Dev/react-the-road-to-enterprise/node_modules/.pnpm/vite@3.2.4_ajklay5k626t46b6fyghkbup3i/node_modules/vite/dist/node/chunks/dep-67e7f8ab.js:39971:19)
    at Context.buildStart (file:///Users/casey/Dev/react-the-road-to-enterprise/node_modules/.pnpm/vite-plugin-stylelint@3.0.2_ob6wbqjaxhaqcketchi7ll2j5i/node_modules/vite-plugin-stylelint/dist/index.mjs:1:2251)
    at async Promise.all (index 4)
    at async hookParallel (file:///Users/casey/Dev/react-the-road-to-enterprise/node_modules/.pnpm/vite@3.2.4_ajklay5k626t46b6fyghkbup3i/node_modules/vite/dist/node/chunks/dep-67e7f8ab.js:39862:9)
    at async Object.buildStart (file:///Users/casey/Dev/react-the-road-to-enterprise/node_modules/.pnpm/vite@3.2.4_ajklay5k626t46b6fyghkbup3i/node_modules/vite/dist/node/chunks/dep-67e7f8ab.js:40133:13)
    at async file:///Users/casey/Dev/react-the-road-to-enterprise/node_modules/.pnpm/vite@3.2.4_ajklay5k626t46b6fyghkbup3i/node_modules/vite/dist/node/chunks/dep-67e7f8ab.js:61879:13)
    at async httpServer.listen (file:///Users/casey/Dev/react-the-road-to-enterprise/node_modules/.pnpm/vite@3.2.4_ajklay5k626t46b6fyghkbup3i/node_modules/vite/dist/node/chunks/dep-67e7f8ab.js:61894:17)
 ELIFECYCLE  Command failed with exit code 1.

项目配置文件

vite.config.ts

/// <reference types="vitest" />

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { fileURLToPath, URL } from 'url';
import eslint from 'vite-plugin-eslint';
import StylelintPlugin from 'vite-plugin-stylelint';
// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    react(),
    eslint(),
    StylelintPlugin({
      fix: true,
      quiet: false,
    }),
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url)),
      'test-utils': fileURLToPath(
        new URL('./src/helpers/test-utils.tsx', import.meta.url)
      ),
    },
  },
  css: {
    preprocessorOptions: {
      scss: {
        // example : additionalData: `@import "./src/styles/variables";`
        // There is need to include the .scss file extensions.
        additionalData: `@import "./src/styles/variables";`,
      },
    },
  },
  test: {
    globals: true,
    environment: 'jsdom',
    coverage: {
      reporter: ['text', 'json', 'html'],
    },
    setupFiles: ['./vitest.setup.ts'],
  },
});

tsconfig.json

{
  "compilerOptions": {
    "baseUrl": ".",
    "target": "ESNext",
    "useDefineForClassFields": true,
    "lib": ["DOM", "DOM.Iterable", "ESNext"],
    "allowJs": false,
    "skipLibCheck": true,
    "esModuleInterop": false,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "paths": {
      "@/*": ["src/*"],
      "test-utils": ["src/helpers/test-utils"]
    }
  },
  "include": ["src"],
  "references": [{ "path": "./tsconfig.node.json" }]
}

stylelint.config.cjs

/* eslint-env node */
module.exports = {
  extends: [
    'stylelint-config-standard',
    'stylelint-config-recess-order',
    'stylelint-config-css-modules',
    'stylelint-config-prettier',
    // Uncomment out the below if you want to use scss
    'stylelint-config-standard-scss',
    'stylelint-config-recommended-scss',
  ],
  plugins: ['stylelint-scss'],
  ignoreFiles: [
    './node_modules/**/*.css',
    './dist/**/*.css',
    './coverage/**/*.css',
  ],
  rules: {
    'at-rule-no-unknown': [
      true,
      {
        ignoreAtRules: [
          'tailwind',
          'apply',
          'screen',
          'variants',
          'responsive',
        ],
      },
    ],
    'no-duplicate-selectors': null,
    'no-empty-source': null,
    'rule-empty-line-before': null,
    'comment-empty-line-before': null,
    'selector-pseudo-element-no-unknown': null,
    'declaration-block-trailing-semicolon': null,
    'no-descending-specificity': null,
    'string-no-newline': null,
    // Limit the number of universal selectors in a selector,
    // to avoid very slow selectors
    'selector-max-universal': 1,
    'selector-class-pattern': '^[a-z][a-zA-Z0-9]+$',
    // --------
    // SCSS rules
    // --------
    'scss/dollar-variable-colon-space-before': 'never',
    'scss/dollar-variable-colon-space-after': 'always',
    'scss/dollar-variable-no-missing-interpolation': true,
    'scss/dollar-variable-pattern': /^[a-z-]+$/,
    'scss/double-slash-comment-whitespace-inside': 'always',
    'scss/operator-no-newline-before': true,
    'scss/operator-no-unspaced': true,
    'scss/selector-no-redundant-nesting-selector': true,
    // Allow SCSS and CSS module keywords beginning with `@`
    'scss/at-rule-no-unknown': null,
  },
}

postcss.config.cjs

/* eslint-disable @typescript-eslint/no-var-requires */
/* eslint-env node */
module.exports = {
  plugins: [
    require('postcss-flexbugs-fixes'),
    require('stylelint')({
      configFile: 'stylelint.config.js',
    }),
    require('postcss-import'),
    require('postcss-extend'),
    require('postcss-mixins'),
    // Comment out postcss-nested if you're using tailwindcss/nesting
    require('postcss-nested'),
    require('tailwindcss/nesting'),
    require('tailwindcss')('tailwind.config.js'),
    require('postcss-preset-env', {
      autoprefixer: {
        flexbox: 'no-2009',
      },
      stage: 3,
      features: {
        'custom-properties': false,
        'nesting-rules': false,
      },
    }),
    require('autoprefixer')(),
    require('postcss-reporter'),
  ],
};

tailwind.config.cjs

const colors = require('tailwindcss/colors');

module.exports = {
  content: ['./index.html', './src/**/*.{js,ts,jsx,tsx}'],
  theme: {
    extend: {},
  },
  // Add only if you want to use the @tailwindcss/forms package
  plugins: [require('@tailwindcss/forms')],
};

prettier.config.cjs

/* eslint-env node */
module.exports = {
  endOfLine: 'lf',
  jsxSingleQuote: true,
  printWidth: 80,
  proseWrap: 'never',
  quoteProps: 'as-needed',
  semi: true,
  singleQuote: true,
  tabWidth: 2,
  trailingComma: 'es5',
  useTabs: false,
};

问题原因及解决步骤

原因分析

  1. 模块格式冲突:Vite 3采用ESM模块系统,而vite-plugin-stylelint@3.0.2内部使用了CommonJS的动态require语法,导致ESM环境下无法兼容。
  2. 重复配置冲突:同时在vite.config.ts中启用了vite-plugin-stylelint,又在postcss.config.cjs中引入了stylelint插件,双重加载引发错误。
  3. 配置文件路径错误:postcss中指定的stylelint配置文件是stylelint.config.js,但实际文件是stylelint.config.cjs,路径不匹配。

解决步骤

  1. 移除PostCSS中的stylelint插件
    编辑postcss.config.cjs,删除require('stylelint')({ configFile: 'stylelint.config.js' })这一行,因为vite-plugin-stylelint已经负责在构建流程中检查样式代码,无需在PostCSS中重复配置。

  2. 升级vite-plugin-stylelint版本
    运行以下命令安装兼容Vite 3的最新版本插件:

    pnpm add vite-plugin-stylelint@latest -D
    # 或使用npm
    npm install vite-plugin-stylelint@latest --save-dev
    
  3. 验证配置
    重新运行pnpm run dev或npm run dev,确认服务正常启动。如果仍有问题,检查stylelint.config.cjs是否正确被加载,可在vite-plugin-stylelint配置中显式指定配置文件路径:

    StylelintPlugin({
      fix: true,
      quiet: false,
      configFile: './stylelint.config.cjs'
    })
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 23:15:41