postcss-import: building from several files
When there are many styles, it is convenient to split them into files: base styles in one, the post card in another. A plain CSS @import makes the browser download each file with a separate request. The postcss-import plugin performs @import at build time: it puts the contents of the files in place of the statements, and the browser gets one file.
Installing
npm install --save-dev postcss-importThe plugin goes first in the list — the others must receive the already joined CSS:
// postcss.config.js
import postcssImport from 'postcss-import';
import postcssPresetEnv from 'postcss-preset-env';
export default {
plugins: [postcssImport(), postcssPresetEnv()],
};Splitting into files
Arrange the blog styles like this:
blog/
├── styles/
│ ├── main.css ← entry point
│ ├── base.css
│ └── post-card.css
└── postcss.config.jsCreate styles/base.css and styles/post-card.css:
/* styles/base.css */
body {
margin: 0;
font-family: system-ui, sans-serif;
}/* styles/post-card.css */
.post-card {
padding: 16px;
border-radius: 8px;
}In styles/main.css, include them at the top of the file:
/* styles/main.css */
@import "./base.css";
@import "./post-card.css";
.post-list {
display: grid;
gap: 16px;
}To see what postcss-import does by itself, temporarily keep only it in plugins and run npx postcss styles/main.css -o css/main.css:
body {
margin: 0;
font-family: system-ui, sans-serif;
}
.post-card {
padding: 16px;
border-radius: 8px;
}
.post-list {
display: grid;
gap: 16px;
}In place of the @import statements are the file contents, in the same order. You process only main.css: the other files end up inside it. Put postcss-preset-env back in the list — it processes the joined file, and @custom-media declarations from any included file are visible everywhere.
CSS from npm packages
postcss-import also looks for files in node_modules. For example, the modern-normalize style reset:
npm install modern-normalize/* styles/main.css */
@import "modern-normalize";
@import "./base.css";
@import "./post-card.css";A package name without a path is enough — the plugin finds its CSS file. In css/main.css the modern-normalize code comes first.
Not needed in Vite
Vite joins @import by itself, so Vite projects do not install postcss-import. You need the plugin when you run PostCSS through postcss-cli.
Common mistake
Putting @import after rules. By the CSS standard, every @import must come at the very top of the file. postcss-import prints the warning @import statements must precede all other statements and drops that import from the result. Keep all @import lines first in the file.