How to set up StandardJS in your project
Last update: 2023-07-12 with configuration for Next.js projects.
Today, I wanted to install StandardJS in a project and, once again, the available documentation is incomplete and doesn't provide usable instructions for what I need: making StandardJS format the code on save in VSCode. 😡
After going over a previous project, these are the steps that worked for me. (Thanks to whoever told me how to make it work on a stream! I think the instructions were taken from a video by Miguel Ángel Durán @midudev)
Install StandardJS in your project
pnpm install standard --save-dev
If not installed, install the StandardJS plugin for VSCode
The StandardJS plugin for VSCode shows alerts editing.
Configure package.json
For StandardJS to format the file on save, we need to add this declaration in the package.json
file of the project:
{
// previous settings ...
"standard": {
"format": true
}
}
// previous settings ...
"eslintConfig": {
"extends": "./node_modules/standard/eslintrc.json"
}
I have no idea why this specific configuration needs to be referenced this way, but this works.
UPDATE: Configure .eslintrc.json
on Next.js projects
If you are using Next.js you probably have an .eslintrc.json file in your project. You need to add the following to the file:
{
"extends": "./node_modules/standard/eslintrc.json"
}
Of course, if you already have an extends
declaration, you can add the StandardJS configuration to the existing one, by placing all the extensions in an Array, like this:
{
"extends": ["next/core-web-vitals", "./node_modules/standard/eslintrc.json"]
}
How to run StandardJS manually on project files
To process all the files in the project, we can run this command from the terminal:
npx standard --fix
** Note: While StandardJS fixes the format to fit its rules, it can't fix all the errors reported by the linter.
Any errors that can't be fixed, will be reported in the terminal after running the script.
In this example, the linter reports an error: A variable is declared but never used.
npx standard --fix
standard: Use JavaScript Standard Style (https://standardjs.com)
/Users/[...]/src/pages/index.js:1:10: 'config' is defined but never used. (no-unused-vars)
To fix this error, we need to delete the variable config
in line 1, column 10 of src/pages/index.js
.