最新公告
  • 欢迎您光临起源地模板网,本站秉承服务宗旨 履行“站长”责任,销售只是起点 服务永无止境!立即加入钻石VIP
  • 基于create-react-app的优化和eslint配置

    正文概述 掘金(Rise_11)   2020-12-29   547

    这是对现有的项目基于create-react-app做的优化

    如果项目中使用了yarn eject

    • 这种方式把配置暴露出来了,可以参考其他文章基于webpack做一些优化

    使用@craco/craco来重写webpack配置

    • 安装此插件 yarn add @craco/craco -D
    • 更改package.json中的script指令
        
    "scripts": {
    - "start": "react-scripts start",
    + "start": "craco start",
    - "build": "react-scripts build",
    + "build": "craco build"
    - "test": "react-scripts test",
    + "test": "craco test"
    }
        
    
    • 在项目的根目录建立 craco.config.js, 配置文件如下:

    注意某些模块需要自己安装

    const path = require('path')
    const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer') // 分析模板依赖大小用的,我这边只配置了在开发时打开服务器
    const CompressionWebpackPlugin = require('compression-webpack-plugin') // 打包时压缩代码成gz,如果服务器开启了gzip可以大大压缩大小
    const CracoLessPlugin = require('craco-less') // 配合按需加载antd 和 修改主题使用
    const WebpackBar = require('webpackbar') // 显示打包进度条用的
    const HardSourceWebpackPlugin = require('hard-source-webpack-plugin') // 缓存用的,第二次打包和构建会极大提升速率
    
    const resolve = (dir) => path.resolve(__dirname, dir)
    const env = process.env.REACT_APP_ENV
    
    const getAnalyzerConfig = (env) => {
      if (env === 'production') {
        return {
          analyzerMode: 'disabled'
        }
      }
    }
    
    module.exports = ({ env: webpackEnv }) => {
      return {
        webpack: {
          plugins: [
            new BundleAnalyzerPlugin(
              Object.assign(
                {},
                {
                  analyzerPort: 'auto',
                  openAnalyzer: webpackEnv !== 'production',
                  generateStatsFile: false,
                  defaultSizes: 'gzip',
                  analyzerMode: 'server'
                },
                getAnalyzerConfig(webpackEnv)
              )
            ),
            new CompressionWebpackPlugin({
              filename: '[path].gz[query]',
              algorithm: 'gzip',
              test: new RegExp('\\.(' + ['js', 'css'].join('|') + ')$'),
              threshold: 1024,
              minRatio: 0.8
            }),
            new WebpackBar({
              name: webpackEnv !== 'production' ? '正在启动' : '正在打包',
              color: '#fa8c16'
            }),
            new HardSourceWebpackPlugin()
          ],
          alias: {
            '@': resolve('src')
          },
          // configure这里可以拿到create-react-app的所有webpack配置,某些在外面修改不了的配置,可以在这配置
          configure: (webpackConfig, { env: webpackEnv, paths }) => {
            // console.log(env, paths)
            paths.appBuild = path.join(path.dirname(paths.appBuild), `build-${env}`)
            webpackConfig.output = {
              ...webpackConfig.output,
              ...{
                path: paths.appBuild
              }
            }
            webpackConfig.devtool = webpackEnv !== 'production' ? 'eval-source-map' : 'none'
            return webpackConfig
          }
        },
        // 下面是antd 的按需加载用的,不用每次导入css文件
        babel: {
          plugins: [
            [
              'import',
              {
                libraryName: 'antd',
                libraryDirectory: 'es',
                style: true
              }
            ]
          ]
        },
        plugins: [
          {
            plugin: CracoLessPlugin,
            options: {
              lessLoaderOptions: {
                lessOptions: {
                  modifyVars: {
                    '@primary-color': '#1890ff'
                  }, //主题颜色
                  javascriptEnabled: true
                }
              }
            }
          }
        ]
      }
    }
    
    
    

    添加eslint

    1. 安装所需要的依赖
    yarn add eslint-config-prettier eslint-plugin-prettier prettier -D
    
    1. 去掉package.json 里面的eslint字段
    - "eslintConfig": {
    -    "extends": "react-app"
    -  }
    
    1. 项目根目录增加.editorconfig .prettierrc .eslintrc.json .env文件
    .editorconfig 文件
    
    root = true
    
    [*]
    indent_style = space
    indent_size = 2
    charset = utf-8
    trim_trailing_whitespace = true
    insert_final_newline = true
    end_of_line = lf
    
    [*.md]
    trim_trailing_whitespace = true
    
    .prettierrc 文件
    
    {
      "trailingComma": "none",
      "tabWidth": 2,
      "semi": false,
      "singleQuote": true,
      "jsxSingleQuote": true,
      "endOfLine": "lf",
      "printWidth": 120,
      "bracketSpacing": true,
      "arrowParens": "always",
      "useTabs": false
    }
    
    .eslintrc.json 文件
    
    {
      "extends": ["react-app", "prettier"],
      "plugins": ["prettier"],
      "rules": {
        "prettier/prettier": ["error", { "endOfLine": "lf" }],
        "@typescript-eslint/no-unused-vars": ["error"],
        "jsx-quotes": [1, "prefer-single"],
        "no-class-assign": "error",
        "no-dupe-keys": "error",
        "no-dupe-args": "error",
        "no-duplicate-case": "error",
        "no-fallthrough": "error",
        "no-func-assign": "error",
        // "linebreak-style": [0, "windows"],
        "no-multi-spaces": "warn",
        "no-var": "error",
        "eqeqeq": [2, "allow-null"],
        "quotes": [1, "single"],
        "no-unreachable": "error",
        "no-multiple-empty-lines": [2, { "max": 2 }],
        "camelcase": "warn",
        "react/jsx-key": 2,
        "react/jsx-max-props-per-line": 0,
        "space-infix-ops": "error"
      }
    }
    
    .env文件
    
    EXTEND_ESLINT=true
    
    
    
    
    1. 增加本项目vscode的设置,根目录下建立一个.vscode文件夹,在里面建立一个settings.json
    settings.json文件
    
    {
        "eslint.validate": [
          "javascript",
          "javascriptreact",
          "typescript",
          "typescriptreact"
        ],
        "editor.formatOnSave": true,
        "javascript.format.enable": false,
        "typescript.format.enable": false,
        "editor.codeActionsOnSave": {
          "source.fixAll.eslint": true
        }
      }
      
    
    
    1. 需要注意安装和开启vscode的ESLint 和 Prettier - Code formatter 插件

    起源地下载网 » 基于create-react-app的优化和eslint配置

    常见问题FAQ

    免费下载或者VIP会员专享资源能否直接商用?
    本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
    提示下载完但解压或打开不了?
    最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,若小于网盘提示的容量则是这个原因。这是浏览器下载的bug,建议用百度网盘软件或迅雷下载。若排除这种情况,可在对应资源底部留言,或 联络我们.。
    找不到素材资源介绍文章里的示例图片?
    对于PPT,KEY,Mockups,APP,网页模版等类型的素材,文章内用于介绍的图片通常并不包含在对应可供下载素材包内。这些相关商业图片需另外购买,且本站不负责(也没有办法)找到出处。 同样地一些字体文件也是这种情况,但部分素材会在素材包内有一份字体下载链接清单。
    模板不会安装或需要功能定制以及二次开发?
    请QQ联系我们

    发表评论

    还没有评论,快来抢沙发吧!

    如需帝国cms功能定制以及二次开发请联系我们

    联系作者

    请选择支付方式

    ×
    迅虎支付宝
    迅虎微信
    支付宝当面付
    余额支付
    ×
    微信扫码支付 0 元