vue3项目实现保存自动格式化

这一次,我们以vue3项目为例。实现在项目中保存文件,自动格式化。包括js语法,css样式格式化和html的标签格式化;

我们用vite新建一个项目:

1,我们在项目总安装如下依赖:

(1)安装ESLint:

npm i -D eslint eslint-plugin-vue @typescript-eslint/parser @typescript-eslint/eslint-plugin

(2)安装Prettier

npm i -D prettier eslint-config-prettier eslint-plugin-prettier

2 我们在根目录下新建.eslintrc.js文件

module.exports = {
  root: true,
  env: {
    node: true
  },
  extends: [
    'plugin:vue/vue3-essential',
    'eslint:recommended',
    '@vue/typescript/recommended',
    '@vue/prettier',
    '@vue/prettier/@typescript-eslint',
    'plugin:prettier/recommended'
  ],
  parserOptions: {
    parsar: '@typescript-eslint/parsar',
    ecmaVersion: 2020,
    sourceType: 'module'
  },
  rules: {
    'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off'
  }
}

3 在项目跟目录下新建 .prettierrc.js 文件

module.exports = {
  printWidth: 120, // 换行字符串阈值
  tabWidth: 2, // 设置工具每一个水平缩进的空格数
  useTabs: false,
  semi: false, // 句末是否加分号
  vueIndentScriptAndStyle: true,
  singleQuote: true, // 用单引号
  trailingComma: 'none', // 最后一个对象元素符加逗号
  bracketSpacing: true,
  jsxBracketSameLine: true, // jsx > 是否另取一行
  arrowParens: 'always', // 不需要写文件开头的 @prettier
  insertPragma: false, // 不需要自动在文件开头加入 @prettier
  endOfLine: 'lf' // 换行符使用 lf
}

4 在根目录下新建一个.vscode文件夹。在里面再新建一个.settings.json,用来设置vscode的全局配置

{
  "editor.fontSize": 20, // 编辑器字体大小
  "terminal.integrated.fontSize": 18,	// terminal 框的字体大小
  "editor.tabSize": 2, // Tab 的大小 2个空格
  "editor.formatOnSave": true, // 保存是格式化
  "prettier.singleQuote": true, // 单引号
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "[vue]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  "eslint.format.enable": true,
  "eslint.validate": [
    "javascript",
    "javascriptreact",
    "html",
    "vue",
    "typescript",
    "typescriptreact"
  ],

}

5 关闭vscode。再次启动。保存就会自动格式化

你可能感兴趣的:(vue,前端,vscode)