vscode eslint beautify 格式化 html

2 篇文章 0 订阅
1 篇文章 0 订阅

新建项目

新建 eslint_html 项目,键入’!'生成代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
</body>
</html>

安装 Beautify 插件

eslint 不支持格式化html 标签内容,默认格式化工具不支持自定义配置,使用该插件自定义格式化。

在项目中新建 .jsbeautifyrc文件,内容如下

{
  "indent_size": 2,
  "indent_char": " "
}

该配置 让 html 标签以 2空格 缩进

eslint 配置

准备好node 环境 安装 eslint和 vscode eslint 插件

初始化npm配置
npm init

回车,按默认配置执行

eslint 初始化
# eslint --init
? How would you like to use ESLint? To check syntax, find problems, and enforce code style
? What type of modules does your project use? None of these
? Which framework does your project use? None of these
? Does your project use TypeScript? No
? Where does your code run? Browser
? How would you like to define a style for your project? Use a popular style guide
? Which style guide do you want to follow? Google: https://github.com/google/eslint-config-google
? What format do you want your config file to be in? JavaScript
Checking peerDependencies of eslint-config-google@latest
Local ESLint installation not found.
The config that you've selected requires the following dependencies:

eslint-config-google@latest eslint@>=5.16.0
? Would you like to install them now with npm? Yes
Installing eslint-config-google@latest, eslint@>=5.16.0
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN eslint_html@1.0.0 No description
npm WARN eslint_html@1.0.0 No repository field.

+ eslint@6.8.0
+ eslint-config-google@0.14.0
added 124 packages from 84 contributors in 6.591s

2 packages are looking for funding
  run `npm fund` for details

Successfully created .eslintrc.js file in xxxxxxx/xxxx

我采用google标准,也可以采用其他标准

写入测试代码

html 中键入以下内容

<script>
  let a = 1
  console.log("a:", a)
</script>
安装eslint html 插件
npm install eslint-plugin-html --dev-save

该步骤很必要,否则不会检测html文件
.eslintrc.js 文件加入如下配置

'plugins': ['html'],
vscode 配置文件
{
    "[html]": {
    	// 使用beautify格式化 html 文件
        "editor.defaultFormatter": "HookyQR.beautify",
        // 保存html时会使用eslint 格式化 script标签中的内容
        "editor.codeActionsOnSave": {
        "source.fixAll.eslint": true
        }
    }
}
完成校验,此时html 中文件应该会出现错误提示

如图
在这里插入图片描述

按ctrl + s 保存会自动按 es6 标准修复

<script>
  const a = 1;
  console.log('a:', a);
</script>

自定义rule

在.eslintrc.js 键入自定义规则定义标准

	'rules': {
    semi: ['error', 'never']
  },

添加js 不以分号结尾

结束

ctrl+s 和 ctrl+shift+f 格式化及修复,如下

<script>
  const a = 1
  console.log('a:', a)
</script>

该项目以放入 github,可直接作为模板使用

https://github.com/gostarcraft/eslint_html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值