如何用stylelint检测多CSS文件重复选择器并保留单文件结果?
Nice question! Since you can’t merge your CSS files but still need to track down duplicate selectors across them and get clear per-file results, here’s a step-by-step way to set this up with stylelint:
1. Install Required Dependencies
First off, you’ll need stylelint itself plus a specialized plugin that handles cross-file duplicate checks—vanilla stylelint only looks for duplicates within a single file. Run this in your project directory:
npm install stylelint stylelint-plugin-cross-file-duplicates --save-dev
2. Configure Stylelint Rules
Create or update a .stylelintrc.json file in your project root to enable the cross-file duplicate detector. Here’s a basic working config:
{ "plugins": ["stylelint-plugin-cross-file-duplicates"], "rules": { "plugin/cross-file-duplicates/selector": [ true, { "message": "Selector `{{selector}}` is duplicated in these files: {{files}}", "ignoreSelectors": [] // Optional: Add selectors to ignore (e.g., `*`, `body` for resets) } ] } }
This rule scans all your target CSS files, flags duplicates, and generates a clear message with the selector name and all files containing it.
3. Set Up a Detection Command
Add a script to your package.json so you can run the check easily. Adjust the file glob (like "src/**/*.css") to match your project’s CSS file structure:
{ "scripts": { "lint:css-duplicates": "stylelint \"src/**/*.css\"" } }
Run the command with:
npm run lint:css-duplicates
4. Interpret the Results
You’ll get output that looks something like this for each duplicate:
src/styles/header.css:5:1: Selector
.nav-linkis duplicated in these files: src/styles/header.css, src/styles/footer.css
Each entry tells you exactly which selector is duplicated and which files it appears in—perfect for targeting specific files to clean up redundant code.
Extra Tips for a Smoother Workflow
- For more readable output, use a pretty formatter like
stylelint-formatter-pretty:
Update your command to use it:npm install stylelint-formatter-pretty --save-devstylelint "src/**/*.css" --formatter=stylelint-formatter-pretty - If you have universal selectors (like reset styles) that you don’t want flagged, add them to the
ignoreSelectorsarray in your config to avoid false positives.
This setup lets you detect cross-file duplicates without merging your CSS files, giving you the per-file context you need to clean up efficiently!
内容的提问来源于stack exchange,提问作者Sivanatarajan

