背景
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
就好了。