Next.js + TS 从零开始写一个前端导航页面(五、添加 eslint 校验)

写了几天的代码发现,没有 eslint 确实对代码格式不太友好,虽然有 TS 支撑,但还是觉得应该把 eslint 加上。

安装依赖

1
$ npm install --save-dev eslint babel-eslint eslint-loader eslint-plugin-jsx-control-statements eslint-plugin-react @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-friendly-formatter

修改配置

根目录 next.config.js 新增以下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
module.exports = {
/**
* buildId - 字符串类型,构建的唯一标示
* dev - Boolean型,判断你是否在开发环境下
* isServer - Boolean 型,为true使用在服务端, 为false使用在客户端.
* defaultLoaders - 对象型 ,内部加载器, 你可以如下配置
* babel - 对象型,配置 babel-loader.
* hotSelfAccept - 对象型, hot-self-accept-loader配置选项.这个加载器只能用于高阶案例。如 @zeit/next-typescript添加顶层 typescript 页面。
*/
webpack: (config, { buildId, dev, isServer, defaultLoaders }) => {
if (dev) {
config.module.rules.push({
test: /\.(js|jsx|ts|tsx)$/,
loader: 'eslint-loader',
enforce: 'pre', // 编译前检查
exclude: [/node_modules/, /\.next/], // 不检测的文件
// include: [resolve('src')], // 指定检查的目录
options: {
// 这里的配置项参数将会被传递到 eslint 的 CLIEngine
formatter: require('eslint-friendly-formatter'), // 指定错误报告的格式规范
},
});
}
return config;
},
};

包含 sass 环境的 next.config.js 完整配置如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/* eslint-disable */
// https://github.com/zeit/next.js/blob/canary/packages/next/next-server/server/config.ts#L12-L63
const path = require('path');
const withSass = require('@zeit/next-sass');
// js 与 sass 公用变量
const styleVariables = require(path.resolve(__dirname, 'sass/variables.js'));

module.exports = withSass({
sassLoaderOptions: {
prependData: `
${Object.keys(styleVariables).map(key => `\$${key}: ${styleVariables[key]};`).join('\r\n')};
@import "sass/_var.scss";
@import "sass/_mixins.scss";
@import "sass/_math.scss";
`,
},
/**
* buildId - 字符串类型,构建的唯一标示
* dev - Boolean型,判断你是否在开发环境下
* isServer - Boolean 型,为true使用在服务端, 为false使用在客户端.
* defaultLoaders - 对象型 ,内部加载器, 你可以如下配置
* babel - 对象型,配置 babel-loader.
* hotSelfAccept - 对象型, hot-self-accept-loader配置选项.这个加载器只能用于高阶案例。如 @zeit/next-typescript添加顶层 typescript 页面。
*/
webpack: (config, { buildId, dev, isServer, defaultLoaders }) => {
config.resolve.alias = {
...config.resolve.alias,
'@': path.resolve(__dirname),
'components': path.resolve(__dirname, './components'),
'sass': path.resolve(__dirname, './sass'),
'static': path.resolve(__dirname, './static'),
};

if (dev) {
config.module.rules.push({
test: /\.(js|jsx|ts|tsx)$/,
loader: 'eslint-loader',
enforce: 'pre', // 编译前检查
exclude: [/node_modules/, /\.next/], // 不检测的文件
// include: [resolve('src')], // 指定检查的目录
options: {
// 这里的配置项参数将会被传递到 eslint 的 CLIEngine
formatter: require('eslint-friendly-formatter'), // 指定错误报告的格式规范
},
});
}

return config;
},
});

添加 eslint 相关配置

根目录新增 .eslintrc.js 文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
module.exports = {
'root': true,
'extends': [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:jsx-control-statements/recommended', // 需要另外配合babel插件使用
'plugin:react/recommended',
],
'plugins': ['@typescript-eslint', 'react', 'jsx-control-statements'],
'env': {
'browser': true,
'node': true,
'es6': true,
// 'jquery': true
'mocha': true,
'jest': true,
'jsx-control-statements/jsx-control-statements': true // 能够在jsx中使用if,需要配合另外的babel插件使用
},
'parser': '@typescript-eslint/parser',
'parserOptions': {
'sourceType': 'module',
'ecmaFeatures': {
'jsx': true,
'experimentalObjectRestSpread': true
}
},
'globals': {
// 'wx': 'readonly',
},
'settings': {
'react': {
'version': 'detect' // 自动读取已安装的react版本
}
},
'rules': {
// eslint 配置文档 https://eslint.org/docs/rules/
'no-extra-semi': 0, // 禁止不必要的分号
'quotes': ['error', 'single'], // 强制使用单引号
'no-unused-vars': 0, // 不允许未定义的变量
// ...你自己的配置
'no-console': ['warn', { allow: ['warn', 'error'] }],
'eqeqeq': ['warn', 'always'],
'prefer-const': ['error', {'destructuring': 'all', 'ignoreReadBeforeAssign': true}],
// @typescript-eslint 配置文档 https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/README.md
'@typescript-eslint/indent': ['error', 2, { VariableDeclarator: 2, SwitchCase: 2 }],
'@typescript-eslint/no-unused-vars': 0,
'@typescript-eslint/interface-name-prefix': 0,
'@typescript-eslint/explicit-member-accessibility': 0,
'@typescript-eslint/no-triple-slash-reference': 0,
'@typescript-eslint/ban-ts-ignore': 0,
'@typescript-eslint/no-this-alias': 0,
'@typescript-eslint/triple-slash-reference': ['error', { 'path': 'always', 'types': 'never', 'lib': 'never' }],
'@typescript-eslint/explicit-function-return-type': 0, // 不检测函数返回类型,让 TS 自动推断
// React 校验规则 配置文档 https://github.com/yannickcr/eslint-plugin-react/tree/master/docs/rules
'react/jsx-indent': [2, 2],
'react/jsx-no-undef': [2, { allowGlobals: true }],
'react/prop-types': 0, // 使用了 TS,不需要 再使用 PropTypes 校验
'jsx-control-statements/jsx-use-if-tag': 0
},
};

如此,eslint 就已经完整的加入开发环境,重启项目 npm run dev,如果你已经编写过一些代码,那么估计会有报错提示。

给 VsCode 编辑器添加 eslint 错误提示

Ctrl + Shift + P 调出控制台,输入 install,再在插件版块查找 ESLint,安装,重启 VsCode 即可。

为了统一编辑器配置,建议在项目目录配置 EditorConfig

新增 .editorconfig 文件:

1
2
3
4
5
[*.{js,jsx,ts,tsx,vue}]
indent_style = space
indent_size = 2
trim_trailing_whitespace = true
insert_final_newline = true

配置文档: https://editorconfig.org/

—end—

本文由 linx(544819896@qq.com) 创作,采用 CC BY 4.0 CN协议 进行许可。 可自由转载、引用,但需署名作者且注明文章出处。本文链接为: https://blog.jijian.link/2020-05-06/next-eslint/

如果您觉得文章不错,可以请我喝一杯咖啡!