𝍌 JSDoc plugin for Prettier

A Prettier plugin to format JSDoc blocks.
🍿 Usage
If you are wondering why I built this, go to the Motivation section.
📦 Installation
First, please check the official documentation on how plugins are used.
Just to recap, and focusing in the configuration file approach, there are two ways in which you are probably going to be using this plugin:
1. Adding it to your existing configuration
The simplest use case: you have a configuration with your rules, and you want to add the plugin. You'd need to define the plugins array, if you don't have it already, and add the plugin name to it:
{
"tabWidth": 90,
"plugins": ["@homer0/prettier-plugin-jsdoc"]
}
2. Extending an existing configuration and adding the plugin
This is kind of confusing in the official docs, because it's not linked in the "using plugins" section, but rather in the "using a shareable config" section.
Unfortunately, Prettier doesn't have a way to use and extend an existing configuration with a JSON syntax, so you have to change to a JavaScript file:
import config from '@homer0/prettier-config';
export default {
...config,
plugins: [
...(config.plugins || []),
'@homer0/prettier-plugin-jsdoc'
],
}
⚙️ Options
@description tag
Allow the @description tag
jsdocAllowDescriptionTag | boolean | false |
Whether or not the @description tag can be used on JSDoc blocks. When disabled, if a @description tag is found, its contents will be moved to the block body:
Use the @description tag
jsdocUseDescriptionTag | boolean | false |
Whether or not to use the @description tag when a description is found on the block body or following a type/callback definition.
@example tag
Format @example tags
jsdocFormatExamples | boolean | true |
Whether or not to attempt to format the @example tags using Prettier itself.
Add lines around @example tags' content
jsdocLinesBetweenExampleTagAndCode | int | 1 |
How many lines should there be between an @example tag and its code.
Manage indentation on formatted examples
jsdocIndentFormattedExamples | boolean | true |
Whether or not to add an indentation level to the code snippets of @example tags. The indentation space will be taken from the tabWidth option.
Manage indentation for pseudo code examples
jsdocIndentUnformattedExamples | boolean | false |
Whether or not to add an indentation level to the code snippets of @example tags that couldn't be formatted with Prettier. This is only valid if jsdocFormatExamples is true.
@access tag
Allow @access tag
jsdocAllowAccessTag | boolean | true |
Whether or not the @access tag can be used; if false, when a tag is found, it will replaced with a tag of its value:
Enforce the use of the @access tag
jsdocEnforceAccessTag | boolean | true |
Whether or not to transform the tags @private, @public and @protected into @access [type] tags:
Types with string literals
Format types with string literals
jsdocFormatStringLiterals | boolean | true |
Whether or not to apply transformations to string literal types.
Specify quotes types for string literals
jsdocUseSingleQuotesForStringLiterals | boolean | true |
Whether or not to use single quotes for string literals' types.
Specify space around string literals
jsdocSpacesBetweenStringLiterals | int | 1 |
How many spaces should there be between string literals on a type.
TypeScript types
Use TypeScript casing for basic types
jsdocUseTypeScriptTypesCasing | boolean | true |
Whether or not to transform the casing of the basic types to make them compatible with TypeScript. This applies to string, number, boolean, Object and Array.
Format complex types with Prettier as TypeScript
jsdocFormatComplexTypesWithPrettier | boolean | true |
Whether or not to format complex type definitions (compatibles with TypeScript) using Prettier.
Arrays and objects
Transform arrays into their shorter form
jsdocUseShortArrays | boolean | true |
Whether or not to transform the type Array<type> into type[] when possible. If inside the symbols there's more than a type, the transformation won't happen:
Modify the dot used for the generics of arrays and objects
jsdocFormatDotForArraysAndObjects | boolean | true |
Whether or not to apply transformations regarding the dot Array and Object types can have before their generics (Array.<...):
Ensure the use or not of the dot for the generics of arrays and objects
jsdocUseDotForArraysAndObjects | boolean | true |
If the formatting for dots is enabled, this options will specify whether the dot is added or removed.
Tags
Replace tags synonyms
jsdocReplaceTagsSynonyms | boolean | true |
Whether or not to replace tags synonyms with their official tag.
Sort tags
Whether or not to sort the tags of a JSDoc block.
Tags order
jsdocTagsOrder | array | typetypedefcallbackfunctionmethodclassfileconstantdescriptionclassdescexampleparampropertyreturnstemplateaugmentsextendsthrowsyieldsfireslistensasyncabstractoverrideprivateprotectedpublicaccessdeprecatedauthorversionsincemembermemberofcategoryexternalseeothertodo
|
A list specifying the order in which the the tags of a JSDoc block should be sorted. It supports an other item to place tags that are not on the list.
Rendering
Use columns
jsdocUseColumns | boolean | true |
Whether or not to try to use columns for type, name and description when possible; if false, the descriptions will be moved to a new line.
The alternative:
Group columns
jsdocGroupColumnsByTag | boolean | true |
Whether to respect column alignment within the same tag. For example: all @param tags are aligned with each other, but not with all the @throws tags.
Consistent columns
jsdocConsistentColumns | boolean | true |
This is for when the columns are aligned by tags; if true and one tag can't use columns, no other tag will use them either.
Keep description in the same line when columns are disabled
jsdocDescriptionInTheSameLine | boolean | false |
Whether or not to try to keep the description in the same line when columns are disabled (jsdocUseColumns: false).
Avoid small columns for descriptions
When jsdocUseColumns: true:
jsdocDescriptionColumnMinLength | int | 35 |
When jsdocUseColumns: false and jsdocDescriptionInTheSameLine: true:
jsdocInlineDescriptionMinLength | int | 35 |
When using columns, or when jsdocDescriptionInTheSameLine is enabled, this is the minimum available space the description column must have; if it's less, the description will be moved to a new line.
When columns are enabled when a description is moved, columns will be disabled for the tag, and if consistent columns are enabled, for the entire block.
Why two options for the same thing? Columns have a lot of different options and possible configurations, and I wanted the new behavior to not be attached to any of that: if columns have to be disabled, but you still need to configure a "columns option", it would be confusing.
Tag spacing: Between tag and type
jsdocMinSpacesBetweenTagAndType | int | 1 |
How many spaces should there be between a tag and a type:
* @[tag][<--this-->]{[type]} [name] [description]
Tag spacing: Between type and name
jsdocMinSpacesBetweenTypeAndName | int | 1 |
How many spaces should there be between a type and a name:
* @[tag] {[type]}[<--this-->][name] [description]
Tag spacing: Between name and description
jsdocMinSpacesBetweenNameAndDescription | int | 2 |
How many spaces should there be between a name and a description column.
* @[tag] {[type]} [name][<--this-->][description]
Space between description body and tags
jsdocLinesBetweenDescriptionAndTags | int | 1 |
How many lines should there be between a description body and the tags.
Make sure descriptions are valid sentences
jsdocEnsureDescriptionsAreSentences | boolean | true |
If enabled, it will make sure descriptions start with an upper case letter and end with a period.
Allow descriptions to be on different lines
jsdocAllowDescriptionOnNewLinesForTags | array | classdesclicensedescdescriptionfilefileoverviewoverviewsummary
|
A list of tags that are allowed to have their description on a new line.
Ignore tags for consistent columns
jsdocIgnoreNewLineDescriptionsForConsistentColumns | boolean | true |
If enabled, when evaluating the rule for consistent columns, tags with description on a new line, allowed by jsdocAllowDescriptionOnNewLinesForTags, will be ignored.
Use an inline block for a single tag
jsdocUseInlineCommentForASingleTagBlock | boolean | false |
Whether or not to use a single line JSDoc block when there's only one tag.
Ignore specific tags
jsdocIgnoreTags | array | empty |
A list of tags that should be ignored when formatting JSDoc comments.
Custom width
jsdocPrintWidth | int | 0 (uses printWidth) |
This is an override for the printWidth option, in case the length of the documentation lines needs to be different.
Turn the plugin on and off
jsdocPluginEnabled | boolean | true |
Whether or not the plugin will parse and transform JSDoc blocks.
Let the plugin know that it's being extended
jsdocPluginExtended | boolean | false |
This will prevent the plugin from running from the original package. The idea is for it to be enabled when the plugin is being extended on the implementation.
⚠️ Experimental
jsdocExperimentalFormatCommentsWithoutTags | boolean | false |
By default, the plugin will only parse comments with tags. Use this option, at your own risk, if you want to format blocks without tags.
jsdocExperimentalIgnoreInlineForCommentsWithoutTags | boolean | false |
Whether or not to ignore the jsdocUseInlineCommentForASingleTagBlock option for comments without tags (when jsdocExperimentalFormatCommentsWithoutTags is enabled).
🚫 Ignoring blocks
If you have some blocks where you don't the plugin to make any modification, you can add the @prettierignore tag and it/they will be skipped:
⚡️ Modifying the functionality
While the plugin has enough options to cover most of the common cases, if you find that it doesn't handle some edge case and you don't think it would be a good idea to send a PR, you can easily modify the plugin functionality without having to fork/clone the original repository.
The entire plugin is (mostly) built around tiny functions inside a dependency injection container, so you could take the container and replace the function you want to modify.
First, we have to enable the option jsdocPluginExtended, as it will prevent it from running from the original package, and create a JS file to work:
.prettierrc:
{
"jsdocPluginExtended": true,
"plugins": ["./my-jsdoc-plugin.js"]
}
Now, on our JS file, we'll add the following snippet:
import { get, override } from '@homer0/prettier-plugin-jsdoc/src/fns/app.js';
import { loadFns } from '@homer0/prettier-plugin-jsdoc/src/loader.js';
import { getPlugin } from '@homer0/prettier-plugin-jsdoc/src/fns/getPlugin.js';
loadFns();
export default get(getPlugin)();
That's all that's needed in order to setup the plugin:
get is the access to the dependency injection container, you pass the reference of an original function and it will return either the function or an override.
loadFns is a utility function that imports all the functions of the plugin and loads them on the dependency injection container.
getPlugin basically connects all the functions and returns the plugin definition.
After that, to modify a function, we need to import the original and use override before the call to getPlugin.
Let's say you want to add the synonym params to param (if the plugin finds @params it will be converted to @param):
import { get, override } from '@homer0/prettier-plugin-jsdoc/src/fns/app.js';
import { loadFns } from '@homer0/prettier-plugin-jsdoc/src/loader.js';
import { getPlugin } from '@homer0/prettier-plugin-jsdoc/src/fns/getPlugin.js';
import { getTagsSynonyms } from '@homer0/prettier-plugin-jsdoc/src/fns/constants.js';
loadFns();
const customGetTagsSynonyms = () => ({
...getTagsSynonyms(),
params: 'param',
});
override(getTagsSynonyms, customGetTagsSynonyms);
export default get(getPlugin)();
That's all, the plugin was successfully extended 🎉!
📖 Troubleshooting
Forcing new lines in paragraphs and lists
When writing multiple paragraphs or markdown lists, you might want to force new lines to be respected, for example:
The problem is that the plugin will end up putting those lines together, as it will assume that they are all part of the same paragraph:
It may look like a bug, but this is actually the functionality that formats the the descriptions in order to respect the printWidth/jsdocPrintWidth option.
The way you can solve this is by adding a period at the end of the line, which will tell the plugin that you ended the sentence and that it should respect the line break
🤘 Development
Tasks
test:unit | Runs the unit tests. |
test:e2e | Runs the functional tests. |
test | Runs all tests. |
lint | Lint the modified files. |
lint:all | Lint the entire project code. |
todo | List all the pending to-do's. |
Repository hooks
I use husky to automatically install the repository hooks so...
- The code will be formatted and linted before any commit.
- The dependencies will be updated after every merge.
- The tests will run before pushing.
⚠️ When the linter and formatter runs for staged files, if the file is importing Prettier, it may fail due to Prettier being ESM. This is temporary, and the workaround for now is to run pnpm run lint:all and commit with -n.
Commits convention
I use conventional commits with commitlint in order to support semantic releases. The one that sets it up is actually husky, that installs a script that runs commitlint on the git commit command.
The configuration is on the commitlint property of the package.json.
Releases
I use semantic-release and a GitHub action to automatically release on NPM everything that gets merged to main.
The configuration for semantic-release is on ./releaserc and the workflow for the release is on ./.github/workflow/release.yml.
⚠️ semantic-release requires Node 18 to be installed, so I temporarily removed it form the package.json and it's only installed in the GitHub action, before being used.
Testing
I use Vitest to test the project, both with unit tests and functional tests.
The configurations files are vitest.e2e.config and vitest.unit.config, and the test files are located on /tests.
In the case of the functional tests, there's a special environment on ./tests/utils that loads and parses a list of fixture files in order to save them on the global object. In reality, there's only one test file for the functional tests, the one that reads the global object and dynamically generates the it(...): index.e2e.js.
Linting && Formatting
I use ESlint with my own custom configuration to validate all the JS code. The configuration file for the project code is on ./eslint.config.js. The script that runs it is on ./utils/scripts/lint-all.
For formatting I use Prettier with my custom configuration, and this plugin. The configuration file for the project code is on ./.prettierrc.js.
To-Dos
I use @todo comments to write all the pending improvements and fixes, and Leasot to generate a report. The script that runs it is on ./utils/scripts/todo.
🐞 Validating bugs
You can use the functional tests to validate a scenario in which the plugin is not behaving as you would expect.
Create a file issue.fixture.js in ./tests/e2e/fixtures and add the following code:
module.exports = { only: true, jsdocPrintWidth: 70 };
- The
module.exports defines the plugin options for that specific case. And yes, even though this is now an ESM only project, the fixtures still use module.exports for the options, and that's fine, because they are not modules.
only: true is not a plugin option, but will make the test runner ignore all the other tests, and only run the one you specify.
- Below
//# input you can put any number of comment blocks, in the state you would expect the plugin to pick them.
- Below
//# output you have to put the expected output after formatting the input with the plugin.
- The "input" and "output" are handled as if they were different files, so you can even put functions and real code, they won't be executed though, just formatted.
Then, you can just run run the test for the fixture with pnpm run test:e2e.
Motivation
Let's start with the fact that I really like the functionality of Prettier, but I really dislike their philosophy. I understand what they are trying to achieve, and it makes sense, but "just use it the way I tell you to" doesn't seem like a valid solution to me.
Ok, they won't accept options requests? that's perfect, it doesn't make sense to just add "one more"... but it would be great if it could be open to be extended, but the only way to do that is with a plugin, which means an extra parsing.
Enough rant; I started using Prettier a couple of weeks ago and being a huge fan of JSDoc, I wanted to use it to format JSDoc blocks too, something I've doing using a Node script that I was trying to make into a VSCode plugin :P.
I found prettier-plugin-jsdoc by @hosseinmd, but it (currently) doesn't cover most of the cases I wanted (like columns creations), it's written in TypeScript (which I don't like very much) and if I were to fork and send PRs, it could've taken forever (you can see the commits for this package), also, it seemed like the perfect opportunity to try Ramda and functional programming... so I started a new one.
5 years later...
- HUGE fan of TypeScript, for a couple of years now.
- I hate reading the Ramda code in here.
- Still hate Prettier philosophy.