搭建react项目遇到的问题2022

这篇具有很好参考价值的文章主要介绍了搭建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;
  };

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

const lessRegex = /\.less$/;
const lessModuleRegex = /\.module\.less$/;

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

const modifyVars = {
    'primary-color': '#2372d9',
  }

替换之前的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,
                  }
                }
              ),
            },

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

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

<Dropdown menu={{ userItems }}>
    <a onClick={e => e.preventDefault()}>
      <Space>
        Hover me
        <DownOutlined />
      </Space>
    </a>
  </Dropdown>

正确的是

<Dropdown menu={{ items: userItems }}>
    <a onClick={e => e.preventDefault()}>
      <Space>
        Hover me
        <DownOutlined />
      </Space>
    </a>
  </Dropdown>

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;
    }
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}`]
	},
}

执行时提示需要在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方便很多
cannot read properties of undefined (reading 'get'),JavaScript,react,react.js,javascript,前端文章来源地址https://www.toymoban.com/news/detail-703866.html

到了这里,关于搭建react项目遇到的问题2022的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包