When talking about front-end code styles, everyone thinks of ESLint and Prettier, but ESLint has a lot of configuration items and the two tend to be in conflict, esLint has different styles and there is no better or worse configuration item, and there is so much code in existing projects that it is difficult to identify a code style although it is important. This article only gives a “working” style configuration, and only write vue2 code for vscode, as for the specific configuration items how to configure and other issues are not discussed.

Eslint and prettier

The first step, of course, is to install two editors (vscode) plugins, eslint and prettier, mainly to detect wavy lines while developing. Then set prettier as the default formatting tool, it can format a variety of types of files, including HTML/js/json/JSX/CSS/less/SCSS, etc., can be found in the official documentation. 13, Prettier formatting files do not contain the stylus file. If the stylus is used, Manta’s Stylus Supremacy would need to be installed, but its configuration would have to be in an editor, making it difficult to follow the project. If it is in a Vue file, it can also be formatted using the Vetur plug-in (vetur configuration also depends on the editor and only works for vue files).

Step 2, install dependencies:

npm i -D eslint@latest prettier@latest eslint-config-prettier@latest eslint-plugin-prettier@latest eslint-config-futu@latest vue-eslint-parser@latest eslint-plugin-vue@latest
Copy the code

For projects where front-end code and Node code are placed side by side, it is recommended to initialize NPM in the outermost layer and execute this command, then execute it in both the front-end and node root directories:

npm i -D eslint@latest
Copy the code

The reason for installing ESLint specifically is that I have experimented with the fact that the loading path of ESLint is not constant. When I first open VSCode, I will use the esLint package in the node_modules directory closest to the current file. The loading directory may change or may not change after switching files. Since there is no guarantee that there won’t be another version of ESLint in the node_modules folder, to be on the safe side, install the same version of the dependency package in every directory.

After that, add the following files to the outermost directory:

.eslintrc.js

module.exports = {
    root: true.parser: 'vue-eslint-parser'.parserOptions: {
        sourceType: 'module'.ecmaVersion: 2021,},extends: [
        'eslint:recommended'.'plugin:prettier/recommended'.'plugin:vue/recommended'.'eslint-config-futu',].rules: {
        // Custom rules that override the extension configuration above
        indent: ['error'.4, { SwitchCase: 1}].// Under switch, case should be indented
        'vue/html-indent': ['error'.4].// Conflict with Prettier, hereby set
        'vue/max-attributes-per-line': 0.// Conflict with Prettier, hereby set
    },
    env: {
        node: true.browser: true,}};Copy the code

.prettierrc.js

module.exports = {
    useTabs: false.printWidth: 100.endOfLine: 'lf'.singleQuote: true.tabWidth: 4.semi: true.trailingComma: 'es5'.arrowParens: 'always'};Copy the code

Eslint + prettier then esLint + prettier is configured, leaving the specific configuration optional.

Check style file

For files with the suffix CSS /less/ SCSS, run in the outermost directory:

npm i -D stylelint stylelint-config-prettier stylelint-prettier stylelint-config-standard stylelint-order
Copy the code

Add the stylelint.config.js file to the outermost directory:

module.exports = {
    extends: ['stylelint-config-standard'.'stylelint-prettier/recommended'].plugins: ['stylelint-order'.'stylelint-prettier'].rules: {
        'prettier/prettier': true.'order/order': [].'order/properties-order': [].'order/properties-alphabetical-order': true,}};Copy the code

For ease of use, it is recommended to also install the editor plug-in stylelint. If using Stylus, see below.

Force commit validation

Execute the following command in the outermost directory:

npm i -D pre-commit lint-staged@10
Copy the code

The version number is specified because I found that some dependent packages have requirements for NPM version during the test. For example, Lint-staged V11 requires Node 12.13.0 while node10 is used on our on-line machine. In order to prevent unexpected accidents caused by version differences, the same version is used locally. Therefore, only older versions can be installed.

Add the following configuration to package.json in the outermost directory:

    "scripts": {
        "pre-commit": "lint-staged" // Add this sentence to script
    },
    "pre-commit": [
        "pre-commit"]."lint-staged": {
        "*.(css|scss|less|vue)": [
            "prettier --write"."stylelint --fix"]."*.(js|vue)": [
            "prettier --write"."eslint --fix --color"]."*.(html|json)": [
            "prettier --write"]},Copy the code

Prettier can be used to format various types of files when performing git commit, then ESLint or stylelint can check the code and repair it automatically. If the code cannot be repaired automatically, an error will be reported, and the commit can be mandatory if necessary.

stylus

In the previous js/ LESS verification, the editor plug-in reads the configuration file and submits the configuration file for verification and detection. Whereas stylus is different, I’ve found two approaches:

1. Install the VScode plug-in and NPM package of Stylus Supremacy, add the configuration file. Stylintrc, which can be used to format files with the suffix STYL, and vetur to format vUE files. However, there will be no wavy line prompt if the format does not meet the requirements. You can force the NPM package to be formatted with a command at commit time, or you can run the Lint command to check code quality, but warnings cannot be automatically fixed.

2. The same as the above less, use stylelint for verification. In this case, you need to install the editor plug-in stylelint, the special NPM package stylelint-plugin-stylus, and add the configuration file stylelint.config.js. This way, you can write with wavy lines (styl files only), you can call validation and fix it automatically when you commit (though it may not be perfect and may need to be called multiple times), but you can’t format it with shortcut keys (if it’s a Vue file, you can format it with vetur). In addition, if this solution is adopted, the file with the same suffix must not be mixed with other CSS preprocessing languages, because verification is determined by the suffix, and the verification configurations of different languages may conflict.

plan Write time formatting Editor wavy line prompt Check on submission Automatic repair on submission Other instructions
The installationStylus SupremacyVscode plugin and NPM package to add configuration files.stylintrc Write with the suffixstylVue files can be formatted using vetur (configuration files can be read) There is no There is no Formatting problems can be solved; other code quality problems can’t Install if requiredstylintRun commands to detect code quality, but warnings cannot be automatically fixed.
With the abovelessAs well, usestylelintTo verify, you need to install the editor plug-instylelint, dedicated NPM packagestylelint-plugin-stylusAnd add a configuration filestylelint.config.js The suffix forstylFiles cannot be formatted, vue files can be usedveturFormat (cannot read configuration files, only defaults) The suffix forstylThe vue file does not support Supported, but not always perfect and may require multiple calls Note that files with the same suffix cannot be mixed with other CSS preprocessor languages because they are usedstylelint, the verification is determined by suffix. The verification configurations of different languages may conflict.

After consideration, it is recommended to adopt scheme 1 and modify the configuration of the editor (explained later).

Scheme 2 is similar to verifying less, except that the plug-in configuration and verification commands are changed. To adopt solution 1, install vscode Manta’s Stylus Supremacy and add. Stylintrc file locking formatting options to the outermost directory. Please refer to the official documentation:

{
    "blocks": false."brackets": "always"."colons": "always"."colors": "always"."commaSpace": "always"."commentSpace": "always"."cssLiteral": "never"."customProperties": []."depthLimit": false."duplicates": true."efficient": "always"."exclude": []."extendPref": false."globalDupe": false."groupOutputByFile": true."indentPref": 4."leadingZero": "never"."maxErrors": false."maxWarnings": false."mixed": false."mixins": []."namingConvention": false."namingConventionStrict": false."none": "never"."noImportant": true."parenSpace": false."placeholders": "always"."prefixVarsWithDollar": "always"."quotePref": false."reporterOptions": {
        "columns": [
            "lineData"."severity"."description"."rule"]."columnSplitter": ""."showHeaders": false."truncate": true
    },
    "semicolons": "always"."sortOrder": "alphabetical"."stackedProperties": "never"."trailingWhitespace": "never"."universal": false."valid": true."zeroUnits": "never"."zIndexNormalize": false
}
Copy the code

Modify the configuration of the VScode editor, since everyone’s configuration is different, we just need to make sure that the editor configuration is the same for the same project. Create.vscode/settings.json in the project root directory:

{
    "files.autoSave": "onFocusChange"."[vue]": {
        "editor.defaultFormatter": "octref.vetur"
    },
    "[javascript]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "[json]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "[jsonc]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "[html]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "[stylus]": {
        "editor.defaultFormatter": "thisismanta.stylus-supremacy"
    },
    "vetur.format.defaultFormatter.html": "prettier"."vetur.format.defaultFormatter.pug": "prettier"."vetur.format.defaultFormatter.css": "prettier"."vetur.format.defaultFormatter.postcss": "prettier"."vetur.format.defaultFormatter.scss": "prettier"."vetur.format.defaultFormatter.less": "prettier"."vetur.format.defaultFormatter.stylus": "stylus-supremacy"."vetur.format.defaultFormatter.js": "prettier"."vetur.format.defaultFormatter.ts": "prettier"."vetur.format.defaultFormatter.sass": "sass-formatter"
}
Copy the code

Finally, configuration when pay attention to the output panel eslint and prettier plug-in information, don’t have an error, the configuration is completed to restart vscode to take effect.

The above is the result of my recent repeated attempts, energy is limited, it is hard to avoid bias, welcome criticism and correction!