• 搭建react项目遇到的问题2022


    环境

    create-react-app:5.0.1

    node:14.17.6

    webpack:5.64.4

    react:18.2.0

    react-router-dom:6.4.3

    eslint:8.26.0

    husky:8.0.1

    lint-staged:13.0.3

    antd:4.24.0

    系统:windows10

    使用create-react-app创建的项目,释放了配置。

    问题

    1. Cannot read properties of undefined (reading 'getStackAddendum')

    这个报错是在使用react-router-domuseRoutes时候出现的,仔细查看了文档,怎么也没发现自己什么地方写错了。最后找了好久才发现是在配置路由时候引入组件的js文件是空的,导致react无法找到组件内容。

    2. 配置支持antd的定制主题,less文件无法编译,定制的主题无效

    首先需要配置支持less,默认的less-loader的版本是11,官方给的例子是webpack4less-loader的版本是5或者4。使用11版本配置了半天没处理出来,最后安装了指定的5版本进行配置,主要是修改了config/webpack.config.js下的getStyleLoaders方法,这个方法不支持配置最后一个loaderoptions,现在修改成支持配置,所有用到这个方法的地方都需要修改。

    const getStyleLoaders = (cssOptions, preProcessor) => {
        const loaders = [
          isEnvDevelopment && require.resolve('style-loader'),
          isEnvProduction && {
            loader: MiniCssExtractPlugin.loader,
            // css is located in `static/css`, use '../../' to locate index.html folder
            // in production `paths.publicUrlOrPath` can be a relative path
            options: paths.publicUrlOrPath.startsWith('.')
              ? { publicPath: '../../' }
              : {},
          },
          {
            loader: require.resolve('css-loader'),
            options: cssOptions,
          },
          {
            // Options for PostCSS as we reference these options twice
            // Adds vendor prefixing based on your specified browser support in
            // package.json
            loader: require.resolve('postcss-loader'),
            options: {
              postcssOptions: {
                // Necessary for external CSS imports to work
                // https://github.com/facebook/create-react-app/issues/2677
                ident: 'postcss',
                config: false,
                plugins: !useTailwind
                  ? [
                      'postcss-flexbugs-fixes',
                      [
                        'postcss-preset-env',
                        {
                          autoprefixer: {
                            flexbox: 'no-2009',
                          },
                          stage: 3,
                        },
                      ],
                      // Adds PostCSS Normalize as the reset css with default options,
                      // so that it honors browserslist config in package.json
                      // which in turn let's users customize the target behavior as per their needs.
                      'postcss-normalize',
                    ]
                  : [
                      'tailwindcss',
                      'postcss-flexbugs-fixes',
                      [
                        'postcss-preset-env',
                        {
                          autoprefixer: {
                            flexbox: 'no-2009',
                          },
                          stage: 3,
                        },
                      ],
                    ],
              },
              sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
            },
          },
        ].filter(Boolean);
        if (preProcessor) {
          loaders.push(
            {
              loader: require.resolve('resolve-url-loader'),
              options: {
                sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
                root: paths.appSrc,
              },
            },
            {
              loader: require.resolve(preProcessor.loader),
              options: {
                sourceMap: true,
                ...preProcessor.options
              },
            }
          );
        }
        return loaders;
      };
    
    • 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
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81

    const sassModuleRegex = /\.module\.(scss|sass)$/;下面增加

    const lessRegex = /\.less$/;
    const lessModuleRegex = /\.module\.less$/;
    
    • 1
    • 2

    module.exports方法的return上面增加(定制的主题变量)

    const modifyVars = {
        'primary-color': '#2372d9',
      }
    
    • 1
    • 2
    • 3

    替换之前的sass规则,并增加less

    		  {
                  test: sassRegex,
                  exclude: sassModuleRegex,
                  use: getStyleLoaders(
                    {
                      importLoaders: 3,
                      sourceMap: isEnvProduction
                        ? shouldUseSourceMap
                        : isEnvDevelopment,
                      modules: {
                        mode: 'icss',
                      },
                    },
                    {
                      loader: 'sass-loader',
                      options: {}
                    }
                  ),
                  // Don't consider CSS imports dead code even if the
                  // containing package claims to have no side effects.
                  // Remove this when webpack adds a warning or an error for this.
                  // See https://github.com/webpack/webpack/issues/6571
                  sideEffects: true,
                },
                // Adds support for CSS Modules, but using SASS
                // using the extension .module.scss or .module.sass
                {
                  test: sassModuleRegex,
                  use: getStyleLoaders(
                    {
                      importLoaders: 3,
                      sourceMap: isEnvProduction
                        ? shouldUseSourceMap
                        : isEnvDevelopment,
                      modules: {
                        mode: 'local',
                        getLocalIdent: getCSSModuleLocalIdent,
                      },
                    },
                    
                    {
                      loader: 'sass-loader',
                      options: {}
                    }
                  ),
                },
                // Opt-in support for LESS (using .scss or .less extensions).
                // By default we support SASS Modules with the extensions .module.less
                {
                  test: lessRegex,
                  exclude: lessModuleRegex,
                  use: getStyleLoaders(
                    {
                      importLoaders: 3,
                      sourceMap: isEnvProduction
                        ? shouldUseSourceMap
                        : isEnvDevelopment,
                    },
                    {
                      loader: 'less-loader',
                      options: {
                        modifyVars,
                        javascriptEnabled: true,
                      }
                    }
                  ),
                  // Don't consider CSS imports dead code even if the
                  // containing package claims to have no side effects.
                  // Remove this when webpack adds a warning or an error for this.
                  // See https://github.com/webpack/webpack/issues/6571
                  sideEffects: true,
                },
                // Adds support for CSS Modules, but using LESS
                // using the extension .module.less
                {
                  test: lessModuleRegex,
                  use: getStyleLoaders(
                    {
                      importLoaders: 3,
                      sourceMap: isEnvProduction
                        ? shouldUseSourceMap
                        : isEnvDevelopment,
                      modules: {
                        mode: 'local',
                        getLocalIdent: getCSSModuleLocalIdent,
                      },
                    },
                    {
                      loader: 'less-loader',
                      options: {
                        modifyVars,
                        javascriptEnabled: true,
                      }
                    }
                  ),
                },
    
    • 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
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96

    3. React.Children.only expected to receive a single React element child.

    使用antdDropdown时候一触发下拉菜单就报错,使用4.24.0废弃的语法糖没问题,一时怀疑人生。最后才发现是因为自定义了和官方不一样的变量却忘记了修改键

    { userItems }}>
         e.preventDefault()}>
          
            Hover me
            
          
        
      
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    正确的是

    { items: userItems }}>
         e.preventDefault()}>
          
            Hover me
            
          
        
      
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    4. (node:3880) [DEP_WEBPACK_DEV_SERVER_ON_AFTER_SETUP_MIDDLEWARE] DeprecationWarning: 'onAfterSetupMiddleware' option is deprecated. Please use the 'setupMiddlewares' option. (Use node --trace-deprecation … to show where the warning was created) (node:3880) [DEP_WEBPACK_DEV_SERVER_ON_BEFORE_SETUP_MIDDLEWARE] DeprecationWarning: 'onBeforeSetupMiddleware' option is deprecated. Please use the 'setupMiddlewares' option. Starting the development server...

    这个只是一个警告提示,并不影响运行,但是看着很难受,config目录下的webpackDevServer.config.js文件,把onBeforeSetupMiddlewareonAfterSetupMiddleware这两个方法替换成下面代码

        setupMiddlewares: (middlewares, devServer) => {
          if (!devServer) {
            throw new Error("webpack-dev-server is not defined");
          }
          middlewares.unshift({
            name: 'evalSourceMapMiddleware',
            middleware: evalSourceMapMiddleware(devServer),
          });
    
          if (fs.existsSync(paths.proxySetup)) {
            // This registers user provided middleware for proxy reasons
            require(paths.proxySetup)(devServer.app);
          }
    
          middlewares.push({
            name: 'redirectServedPath',
            middleware: redirectServedPath(paths.publicUrlOrPath),
          });
    
          middlewares.push({
            name: 'noopServiceWorkerMiddleware',
            middleware: noopServiceWorkerMiddleware(paths.publicUrlOrPath),
          });
    
          return middlewares;
        }
    
    • 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
    5. lint-staged配置与本地运行冲突

    lint-staged的配置文件lint-staged.config.js里面内容

    import { ESLint } from 'eslint'
    const removeIgnoredFiles = async (files) => {
    	const eslint = new ESLint()
    	const isIgnored = await Promise.all(files.map((file) => {
    		return eslint.isPathIgnored(file)
    	}))
    	const filteredFiles = files.filter((_, i) => !isIgnored[i])
    	return filteredFiles.join(' ')
    }
    
    export default {
    	'src/**/*.{js,jsx}': async (files) => {
    		const filesToLint = await removeIgnoredFiles(files)
    		return [`eslint --fix ${filesToLint}`]
    	},
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    执行时提示需要在package.json内增加type:module,但是本地运行npm start又要去掉package.json内的type:modulelint-staged.config.js可以是ESMCommonJS主要取决于package.json内是否有type:module,代码里面使用的是ESM所以才会出现提示,我们可以通过修改文件名来处理,把lint-staged.config.js修改成lint-staged.config.mjs就可以了

    6. husky的命令行无效

    安装完包,并且配置prepare,必须先在命令行中运行一下prepare
    无效的命令npx husky add .husky/pre-commit "npm run test",这个时win10系统的原因

    修改成npx husky add .husky/pre-commit "npm-run-test",然后去修改文件里面的执行命令;或者修改成npx husky add .husky/pre-commit,然后去增加文件里面的执行命令

    分享

    redux-toolkit中文网

    https://redux-toolkit-cn.netlify.app/

    这个很好用,比起以往使用redux方便很多
    在这里插入图片描述

  • 相关阅读:
    hadoop 数据抽取
    eBay买家号注册下单容易死号?是什么原因导致?
    ClickHouse基本原理
    企微SCRM营销平台MarketGo-ChatGPT助力私域运营
    47 VM.maxDirectMemory() 来自于哪里
    左移运算符重载
    Redis原理 - 对象的数据结构(SDS、Inset、Dict、ZipList、QuickList、SkipList、RedisObject)
    JUC并发编程(一):Java内存模型(JMM)及三大特性:可见性、有序性、原子性
    Redis学习 - 了解Redis(三)
    【算法题】翻转对
  • 原文地址:https://blog.csdn.net/lydxwj/article/details/127839373