Maybe it’s the trend, but recently I’ve been doing mostly frontend work.
I tried my first JavaScript syntax check, so here are my notes.
For syntax checking, I used ESLint.
% npm install eslint --save-dev
"devDependencies": {
"eslint": "^7.0.0"
},
Next, set up ESLint. You don’t have to install it globally; you can use the npx
command, which is convenient.
% npx eslint --init
How would you like to use ESLint?
I wanted to try various things, so I chose the third option: check syntax, find problems, and enforce code style.
? How would you like to use ESLint? (Use arrow keys)
To check syntax only
To check syntax and find problems
➤ To check syntax, find problems, and enforce code style
What type of modules does your project use?
? What type of modules does your project use?
JavaScript modules (import/export)
➤ CommonJS (require/exports)
None of these
Which framework does your project use?
? Which framework does your project use?
React
Vue.js
➤ None of these
Does your project use TypeScript?
Oh! This is the one that integrates TSLint
used in TypeScript
.
? Does your project use TypeScript? (y/N)
Where does your code run?
? Where does your code run?
◯ Browser
➤◉ Node
How would you like to define a style for your project?
You can choose a popular coding guideline, but since it’s my first time, I’ll answer questions to select a style.
? How would you like to define a style for your project?
Use a popular style guide
➤ Answer questions about your style
Inspect your JavaScript file(s)
What format do you want your config file to be in?
When I googled, JSON format was common, but I prefer YAML.
? What format do you want your config file to be in?
JavaScript
➤ YAML
JSON
What style of indentation do you use?
Here comes the faction dispute. I use Tabs.
? What style of indentation do you use? (Use arrow keys)
➤ Tabs
Spaces
What quotes do you use for strings?
? What quotes do you use for strings?
Double
➤ Single
What line endings do you use?
? What line endings do you use? (Use arrow keys)
➤ Unix
Windows
Do you require semicolons?
? Do you require semicolons? (Y/n)
That’s it. A .eslintrc.yml
file has been created.
Let’s try running it.
% npx eslint test.js
Since I installed ESLint
, I also want vscode
to automatically fix code and provide warnings.
So, I installed the ESLint extension supported by Microsoft.
In my case, I set up settings.json
as follows. Although I’m also including settings for tabs and other things, the important part is editor.codeActionsOnSave
. This setting enables automatic fixes by ESLint
upon saving.
"editor.formatOnType": true,
"editor.detectIndentation": false,
"editor.insertSpaces": false,
"editor.renderWhitespace": "all",
"editor.tabSize": 2,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}