环境
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-dom
的useRoutes
时候出现的,仔细查看了文档,怎么也没发现自己什么地方写错了。最后找了好久才发现是在配置路由时候引入组件的js文件是空的,导致react
无法找到组件内容。
2. 配置支持antd的定制主题,less文件无法编译,定制的主题无效
首先需要配置支持less
,默认的less-loader
的版本是11,官方给的例子是webpack4
,less-loader
的版本是5或者4。使用11版本配置了半天没处理出来,最后安装了指定的5版本进行配置,主要是修改了config/webpack.config.js
下的getStyleLoaders
方法,这个方法不支持配置最后一个loader
的options
,现在修改成支持配置,所有用到这个方法的地方都需要修改。
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.
使用antd
的Dropdown
时候一触发下拉菜单就报错,使用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
文件,把onBeforeSetupMiddleware
和onAfterSetupMiddleware
这两个方法替换成下面代码
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:module
,lint-staged.config.js
可以是ESM
或CommonJS
主要取决于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/文章来源:https://www.toymoban.com/news/detail-703866.html
这个很好用,比起以往使用redux
方便很多
文章来源地址https://www.toymoban.com/news/detail-703866.html
到了这里,关于搭建react项目遇到的问题2022的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!