背景
create-react-app
项目构建基于react-scripts
包,webpack相关配置也都在这个包里,webpack
的配置可以跟随react-scripts
包的升级而升级,非常方便。但是在实际项目中我们往往需要自定义
一些配置,但又希望保留这种跟着包升级配置的优势。eslint
是项目中非常常用的工具,它的配置也是因人而异,因项目团队而异。而create-react-app
默认是有一套eslint配置的,并且在webpack
的eslint-loader
配置中设置了useEslintrc
为false
。所以直接在项目中添加eslint.rc
是没用的。
解决办法
添加node环境变量EXTEND_ESLINT
为true
。react-scripts
包中的webpack配置中有一段代码:
{
test: /\.(js|mjs|jsx|ts|tsx)$/,
enforce: 'pre',
use: [
{
options: {
cache: true,
formatter: require.resolve('react-dev-utils/eslintFormatter'),
eslintPath: require.resolve('eslint'),
resolvePluginsRelativeTo: __dirname,
// @remove-on-eject-begin
baseConfig: (() => {
const eslintCli = new eslint.CLIEngine();
let eslintConfig;
try {
eslintConfig = eslintCli.getConfigForFile(paths.appIndexJs);
} catch (e) {
// A config couldn't be found.
}
// We allow overriding the config only if the env variable is set
if (process.env.EXTEND_ESLINT === 'true' && eslintConfig) {
return eslintConfig;
} else {
return {
extends: [require.resolve('eslint-config-react-app')],
};
}
})(),
ignore: false,
useEslintrc: false,
// @remove-on-eject-end
},
loader: require.resolve('eslint-loader'),
},
],
include: paths.appSrc,
},
可以看到当EXTEND_ESLINT
设置为true的时候会启用根目录下的eslint配置。
添加变量
添加node环境变量这里提供两种方式
:
命令行
在package.json中修改scripts,这里以start
命令为例,由于windows,Linux,Mac环境的不同,命令方式也不同,这里安装cross-env
来兼容各个环境。
- 安装
cross-env
npm install --save cross-env
- 添加环境到命令
"script": {
"start": "cross-env EXTEND_ESLINT=true react-scripts start"
}
配置文件
添加.env文件,在文件中添加
EXTEND_ESLINT=true
备注
如果你能够放弃跟包升级,你可以使用npm run eject
来释放webpack以及其他配置,一切回归你的掌控,那么添加自定义的eslint也自然不在话下,只需要把useEslintrc
设置为true
就好了。