如何获得ESLint来整理VSCode中的HTML文件?

Ale*_*ott 7 javascript lint eslint visual-studio-code

我有一个Javascript浏览器项目,该项目分为多个文件,并且无法在同一全局范围内让ESLint整理HTML文件的脚本标签,因此一个文件中的类和函数的声明和调用可以在另一个文件中识别。

这是我的项目结构:

项目结构

这是foo.js的内容:

sayHello();
Run Code Online (Sandbox Code Playgroud)

和bar.js:

function sayHello() {
  console.log('Hello');
}
Run Code Online (Sandbox Code Playgroud)

我已经将它们都链接到了HTML文件中:

<html>
  <head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="main.css">
    <script src="libraries/bar.js" type="text/javascript"></script>
    <script src="foo.js" type="text/javascript"></script>
  </head>
  <body>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

我以为解决此问题的方法是使用eslint-plugin-html软件包,但是尝试配置它没有运气。这些是我在项目本地安装的软件包:

Alexs-MacBook-Pro:Demo alexmcdermott$ npm list --depth=0
demo@1.0.0 /Users/alexmcdermott/GitHub/Demo
??? eslint@5.12.0
??? eslint-config-airbnb-base@13.1.0
??? eslint-plugin-html@5.0.0
??? eslint-plugin-import@2.14.0
Run Code Online (Sandbox Code Playgroud)

我正在使用VSCode编辑器,但在终端中也遇到了相同的问题:

Alexs-MacBook-Pro:Demo alexmcdermott$ npx eslint --ext .js,.html .

/Users/alexmcdermott/GitHub/Demo/foo.js
  1:1  error  'sayHello' is not defined  no-undef

/Users/alexmcdermott/GitHub/Demo/libraries/bar.js
  1:10  error    'sayHello' is defined but never used  no-unused-vars
  2:3   warning  Unexpected console statement          no-console

? 3 problems (2 errors, 1 warning)
Run Code Online (Sandbox Code Playgroud)

与VSCode中的相同:

vscode错误

这是我的ESLint配置:

{
    "env": {
        "browser": true,
        "es6": true
    },
    "extends": "airbnb-base",
    "plugins": [ "html" ]
}
Run Code Online (Sandbox Code Playgroud)

并且我还将VSCode配置为在VSCode用户设置中使用以下选项在HTML文件上运行ESLint:

{
    "eslint.autoFixOnSave": true,
    "eslint.options": {
        "extensions": [ ".js", ".html" ]
    },
    "eslint.validate": [
        "javascript",
        {
            "language": "html",
            "autoFix": true
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

尽管我必须做错了什么,还是错过了eslint-plugin-html的要点?如果有人对我做错了什么或如何解决此问题有任何意见,我将不胜感激,因为我已经坚持了很久了。请让我知道是否需要提供更多信息,这是我的新手。

gma*_*man 12

我有这个 <projectfolder>/.vscode/settings.json

{
  "eslint.validate": [ "javascript", "html" ]
}
Run Code Online (Sandbox Code Playgroud)

我正在使用一个.eslintrc.js看起来像这样的

module.exports = {
  "env": {
    "browser": true,
    "es6": true
  },
  "plugins": [
    "eslint-plugin-html",
  ],
  "extends": "eslint:recommended",
  "rules": {
  }
};
Run Code Online (Sandbox Code Playgroud)

我定义了很多规则,但没有将它们粘贴在上面

结果:

在此处输入图片说明

  • 添加了我的`.eslintrc.js`。我很确定插件部分可以只是“html”。你安装了它吗?`npm install --save-dev eslint-plugin-html`? (3认同)

Dan*_*cki 5

使用eslint-plugin-html

  1. npm install eslint-plugin-html --save-dev在您的终端中运行。
  2. 打开.eslintrc.js并在plugins: ["html"]之后添加module.exports。如果您有.json或不同的格式,.js那么只需遵循模式并在相同的嵌套级别添加相同的值。
  3. ./node_modules/.bin/eslint --ext .html .在您的终端中运行。