postcss-layer-by-path
v1.0.0
Published
PostCSS plugin that wraps file contents in @layer based on glob patterns
Maintainers
Readme
postcss-layer-by-path
A PostCSS plugin that automatically wraps CSS files in @layer blocks based on the file's path matching glob patterns.
Installation
npm install postcss-layer-by-pathUsage
// postcss.config.js
import layerByPath from 'postcss-layer-by-path'
export default {
plugins: [
layerByPath({
'src/components/**/*.css': 'components',
'src/pages/**/*.css': 'pages',
'src/styles/utilities/**/*.css': 'utilities',
}),
],
}Input (src/components/Button.css):
.button { color: red; }
.button:hover { color: darkred; }Output:
@layer components {
.button { color: red; }
.button:hover { color: darkred; }
}Options
The plugin accepts a single argument: a plain object mapping glob patterns to layer names.
layerByPath({
[glob: string]: string
})- Keys — glob patterns matched against the file path (relative to
process.cwd()). Uses micromatch syntax. - Values — the layer name to use in
@layer <name> { ... }. Sub-layers with dots are supported (e.g.'base.reset').
First match wins. Patterns are evaluated in insertion order; the first matching pattern's layer name is used.
Behavior
| Scenario | Result |
|---|---|
| File path matches a pattern | Wrapped in @layer <name> { } |
| No pattern matches | File left unchanged |
| File already has a top-level @layer | File left unchanged |
| Empty file | File left unchanged |
| No file path available (in-memory processing) | File left unchanged |
Examples
Vite
// vite.config.js
import { defineConfig } from 'vite'
import layerByPath from 'postcss-layer-by-path'
export default defineConfig({
css: {
postcss: {
plugins: [
layerByPath({
'src/components/**/*.css': 'components',
'src/pages/**/*.css': 'pages',
}),
],
},
},
})webpack / css-loader
// webpack.config.js
const layerByPath = require('postcss-layer-by-path')
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader',
{
loader: 'postcss-loader',
options: {
postcssOptions: {
plugins: [
layerByPath({
'src/components/**/*.css': 'components',
'src/pages/**/*.css': 'pages',
}),
],
},
},
},
],
},
],
},
}License
MIT
