新建 eslint_html 项目,键入’!'生成代码
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Documenttitle>
head>
<body>
body>
html>
eslint 不支持格式化html 标签内容,默认格式化工具不支持自定义配置,使用该插件自定义格式化。
在项目中新建 .jsbeautifyrc文件,内容如下
{
"indent_size": 2,
"indent_char": " "
}
该配置 让 html 标签以 2空格 缩进
准备好node 环境 安装 eslint和 vscode eslint 插件
npm init
回车,按默认配置执行
# 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 [email protected] No description
npm WARN [email protected] No repository field.
+ [email protected]
+ [email protected]
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>
npm install eslint-plugin-html --dev-save
该步骤很必要,否则不会检测html文件
.eslintrc.js 文件加入如下配置
'plugins': ['html'],
{
"[html]": {
// 使用beautify格式化 html 文件
"editor.defaultFormatter": "HookyQR.beautify",
// 保存html时会使用eslint 格式化 script标签中的内容
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
}
}
按ctrl + s 保存会自动按 es6 标准修复
<script>
const a = 1;
console.log('a:', a);
script>
在.eslintrc.js 键入自定义规则定义标准
如
'rules': {
semi: ['error', 'never']
},
添加js 不以分号结尾
ctrl+s 和 ctrl+shift+f 格式化及修复,如下
该项目以放入 github,可直接作为模板使用
https://github.com/gostarcraft/eslint_html