𝍌 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.
⚙️ 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:
Enfore 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 | type typedef callback function method class file constant description classdesc example param property returns template augments extends throws yields fires listens async abstract override private protected public access desprecated author version since member memberof category external see other todo
|
A list specifing 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 agligned with eachother, but not with all the @throws
tags.
Consistent columns
jsdocConsistentColumns | boolean | true |
This is for when the columns are algined by tags; if true
and one tag can't use columns, no other tag will use them either.
Avoid small columns for descriptions
jsdocDescriptionColumnMinLength | int | 35 |
When using columns, this is the minimum available space the description column must have; if it's less, the description will be moved to a new line and columns will be disabled for the tag, and if consistent columns are enabled, for the entire block.
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 | classdesc license desc description file fileoverview overview summary
|
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.
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.
🚫 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:
const { get, override } = require('@homer0/prettier-plugin-jsdoc/src/fns/app');
const { loadFns } = require('@homer0/prettier-plugin-jsdoc/src/loader');
const { getPlugin } = require('@homer0/prettier-plugin-jsdoc/src/fns/getPlugin');
loadFns();
module.exports = 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 require
s 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.
Now, in order 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
):
const { get, override } = require('@homer0/prettier-plugin-jsdoc/src/fns/app');
const { loadFns } = require('@homer0/prettier-plugin-jsdoc/src/loader');
const { getPlugin } = require('@homer0/prettier-plugin-jsdoc/src/fns/getPlugin');
const { getTagsSynonyms } = require('@homer0/prettier-plugin-jsdoc/src/fns/constants');
loadFns();
const customGetTagsSynonyms = () => ({
...getTagsSynonyms(),
params: 'param',
});
override(getTagsSynonyms, customGetTagsSynonyms);
module.exports = 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
/jsodcPrintWidth
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 npm 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 Jest to test the project, both with unit tests and functional tests.
The configurations files are .jestrc-e2e
and .jestrc-unit
, 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 ./.eslintrc
and the one for the tests is on ./tests/.eslintrc
. There's also an ./.eslintignore
to exclude some files on the process. The script that runs it is on ./utils/scripts/lint-all
.
For formatting I use Prettier with my custom configuration and this same plugin. The configuration file for the project code is on ./.prettierrc
.
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
specifiy the plugin options for that specific case.
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 npm 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" doesn't seem like a valid solution to me.
Ok, there 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. The only way to do it 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, for sometime now, 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), and it seemed like the perfect oportunity to try Ramda and functional programming... so I started a new one.