Env Sorter
A VS Code extension that sorts .env files: variables are clustered by prefix
and each cluster is sorted alphabetically.
It registers as a document formatter for env files, so it runs on
Format Document and on save (with editor.formatOnSave enabled).
Behaviour
- Grouped by prefix. The prefix is the segment before the first
_
(DB_HOST, DB_NAME → the DB group). Each group is separated from the next
by a single blank line. A variable with a unique prefix (or no _) forms its
own one-line block.
- Alphabetical. Groups are ordered by prefix; variables within a group are
ordered by key.
- Comments follow their variable. A run of comment lines directly above a
KEY=VALUE moves with it into its group.
- File header / footer are pinned. Comment lines before the first variable
stay at the top; comment lines after the last variable stay at the bottom.
- Multi-line quoted values are kept intact.
- Stable. Any blank lines the file already had are discarded and
regenerated, so sorting an already-sorted file changes nothing.
Example
# Local dev config
NODE_ENV=development
APP_PORT=3000
APP_NAME=demo
DB_PASSWORD=p@ss
DB_HOST=localhost
STRIPE_SECRET_KEY=sk_test
STRIPE_PUBLIC_KEY=pk_test
DEBUG=true
becomes
# Local dev config
APP_NAME=demo
APP_PORT=3000
DB_HOST=localhost
DB_PASSWORD=p@ss
DEBUG=true
NODE_ENV=development
STRIPE_PUBLIC_KEY=pk_test
STRIPE_SECRET_KEY=sk_test
Settings
| Setting |
Default |
Description |
envSorter.groupByPrefix |
true |
Cluster variables by prefix into blank-line-separated blocks. When false, produces one flat alphabetical list with a blank line wherever the first letter changes. |
envSorter.caseSensitive |
false |
Sort case-sensitively (uppercase before lowercase). When off, FOO and foo sort together. |
- A comment stays attached to a variable only when it sits directly above it
with no blank line between. That comment travels with the variable.
- A comment that is the first non-blank content in the file is treated as a file
header and stays at the top — it is never pulled down next to a variable.
- If a section-header comment (
# Database) sits directly above a variable that
is not the alphabetically-first one in its group, it will end up in the
middle of the group. Put section headers above the first member, or accept
that grouping already keeps the block together without the header.
{
"editor.formatOnSave": true,
"[dotenv]": {
"editor.defaultFormatter": "local.env-sorter"
}
}
The dotenv language is contributed by this extension and matches .env,
.env.*, and *.env files.
Developing
npm install
npm run compile # or: npm run watch
npm test # runs the sorter unit tests
Press F5 in VS Code to launch an Extension Development Host.