Create-react-app 配置自定義eslint

背景

  • create-react-app項目構建基於react-scripts包,webpack相關配置也都在這個包裏,webpack的配置可以跟隨react-scripts包的升級而升級,非常方便。但是在實際項目中我們往往需要自定義一些配置,但又希望保留這種跟着包升級配置的優勢。
  • eslint是項目中非常常用的工具,它的配置也是因人而異,因項目團隊而異。而create-react-app默認是有一套eslint配置的,並且在webpackeslint-loader配置中設置了useEslintrcfalse。所以直接在項目中添加eslint.rc是沒用的。

解決辦法

添加node環境變量EXTEND_ESLINTtruereact-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就好了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章