You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

构建React项目时出现TypeError: Cannot read property 'endsWith' of null错误求助

解决React项目中TypeError: Cannot read property 'endsWith' of null的问题

最近我在搭建React项目的时候踩了个坑,碰到了这个报错:

TypeError: Cannot read property 'endsWith' of null

错误指向C:\Users\Modi\AppData\Roaming\npm\node_modules\react-scripts\config\paths.js:23这一行,对应的代码是:

const hasSlash = inputPath.endsWith('/');

问题原因

这个错误逻辑很明确——代码里的inputPath是null,自然没法调用endsWith方法。一般来说,这是react-scripts没能正确识别项目路径导致的,常见诱因有这几个:

  • 没有在项目根目录下执行启动命令;
  • 全局安装的react-scripts和项目本地版本不兼容;
  • 自定义webpack配置里的路径设置有误,或者项目目录结构不符合预期。

解决方案

我整理了几个亲测有效的解决步骤,你可以挨个试试:

  • 确保在项目根目录执行命令
    先确认终端当前路径是项目根目录(也就是包含package.json、public、src的文件夹),再运行npm start或者yarn start。

  • 处理全局react-scripts版本冲突
    全局安装的react-scripts很容易和项目本地版本打架,建议先卸载全局版本,改用项目本地的:

    1. 执行卸载命令:npm uninstall -g react-scripts
    2. 回到项目根目录,安装本地版本:npm install react-scripts --save
    3. 之后用npx react-scripts start启动项目,这样会优先调用本地的脚本。
  • 检查自定义webpack配置
    你提供的webpack配置如下,重点要确认HtmlWebpackPlugin的template路径是否正确,确保./public/index.html这个文件确实存在:

var HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
 mode: "development",
 resolve: {
 extensions: [".js", ".jsx"],
 },
 module: {
 rules: [
 {
 test: /\.jsx?$/,
 loader: "babel-loader",
 },
 ],
 },
 plugins: [
 new HtmlWebpackPlugin({
 template: "./public/index.html",
 }),
 ],
 devServer: {
 historyApiFallback: true,
 },
 externals: {
 // global app config object
 config: JSON.stringify({
 apiUrl: "/api",
 }),
 },
 };

如果路径没问题,还可以检查项目里的.babelrc或者babel.config.js配置是否正确,确保babel能正常处理jsx文件。

  • 注意create-react-app的特殊情况
    如果你是用create-react-app初始化的项目,除非已经执行了npm run eject,否则不要手动写webpack配置——react-scripts会默认使用自己的配置文件,手动配置不仅不会生效,还可能干扰路径识别逻辑。

内容的提问来源于stack exchange,提问作者vivek modi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 19:32:53