Skip to content

Latest commit

 

History

History
106 lines (82 loc) · 2.25 KB

configuring-eslint-to-implement-code-specification-autotest.md

File metadata and controls

106 lines (82 loc) · 2.25 KB

配置ESLint实现代码规范自动测试

ESLint是一个前端JS代码的规范集,具体参考这里

package.json中的配置

在前端项目,不仅仅是webpack项目中,可以通过下面的方式引入ESLint。

本地安装

npm i eslint --save-dev

配置

  • 修改项目的package.json文件内容
{
  "scripts": {
    "lintjs": "eslint app/ webpack.*.js --cache"
  }
}
  • 添加.eslintrc.js配置文件
const config = {
    env: {
        browser: true,
        commonjs: true,
        es6: true,
        node: true,
    },
    extends: 'eslint:recommended',
    parserOptions: {
        sourceType: 'module',
    },
    rules: {
        'comma-dangle': ['error', 'always-multiline'],
        indent: ['error', 2],
        'linebreak-style': ['error', 'unix'],
        quotes: ['error', 'single'],
        semi: ['error', 'always'],
        'no-unused-vars': ['warn'],
        'no-console': 0,
    },
};

module.exports = config;

上述文件内容放在项目根目录下的.eslintrc.js中。

运行

npm run lintjs

自动修正代码的规范错误可以使用npm run lintjs -- --fix,但是ESLint的版本>= 1.4.0

ESLint在webpack中的应用

安装eslint-loader

npm i eslint-loader --save-dev

配置

配置webpack.config.js文件内容。

const config = {
    devServer: {
        host: process.env.HOST, // Defaults to `localhost`
        port: 9000, // Defaults to 8080
        overlay: {
            errors: true,
            warnings: true,
        },
    },
    // ...
    module: {
        rules: [
            {
                test: /\.js$/,
                enforce: 'pre',

                loader: 'eslint-loader',
                options: {
                    emitWarning: true,
                },
            },
        ],
    },
};

配置modules选项和devServer下的overlay选项(在浏览器中限制错误和警告信息)。