nuxt + eslint + prettier 保存自动格式化

2,304 阅读1分钟

nuxt + eslint + prettier 保存自动格式化(无需配置.vscode/settings.json)

  • 首先安装配置完(编码规范,代码提交规范)全家桶husky+lint-staged+commitlint,详细配置方式请戳 juejin.cn/post/700291… ,然后开始以下配置完成保存时自动格式化

1. 配置.editorconfig文件

# editorconfig.org
root = true
[*]
indent_size = 4 
indent_style = space
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false

2. 配置.prettierrc文件

{
    "singleQuote": true, // 使用单引号 `.vscode/settings.json``prettier.semi`
    "semi": false, // 结尾不加分号 `.vscode/settings.json``prettier.semi`
    "printWidth": 120 // 此项为我自加以上两项为默认,表示每行最多显示的字符数,默认为80,本人觉得太短了,因此修改了一下,必须与`.vscode/settings.json` 的`prettier.printWidth`对应上
    /* 更多配置请转至 https://prettier.io/docs/en/options.html */
}

3. 配置.eslintrc.js文件

module.exports = {

    root: true,
    env: {
        browser: true,
        node: true,
    },
    parserOptions: {
        parser: 'babel-eslint',
    },
    extends: [
        // '@nuxtjs',
        'plugin:nuxt/recommended',
        'plugin:prettier/recommended',
        'prettier',
        'prettier/vue',
    ],
    plugins: ['prettier'],
    // add your custom rules here
    rules: {
        'nuxt/no-cjs-in-config': 'off',
        indent: ['off', 2], // 4个空格缩进
    /* 更多配置请戳 http://eslint.cn/docs/rules/ */
    },
}

4. nuxt.config.js文件下 build.extend(config, ctx) {}添加options.fix: true

build: {
        /*
         ** You can extend webpack config here
         */
        extend(config, ctx) {
            // Run ESLint on save
            if (ctx.isDev && ctx.isClient) {
                config.module.rules.push({
                    enforce: 'pre',
                    test: /.(js|vue)$/,
                    loader: 'eslint-loader',
                    exclude: /(node_modules)/,
                    options: {
                        fix: true
                    }
                })
            }
        }
    }