React项目执行yarn dev/npm run dev时package.json解析错误求助
React项目执行
yarn dev/npm run dev报错排查 报错详情
执行启动命令时出现以下错误:
yarn run v1.22.17 error An unexpected error occurred: "C:\Users\my location\package.json: Unexpected token < in JSON at position 2". info If you think this is a bug, please open a bug report with the information provided in "C:\Users\my location \yarn-error.log". info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
将package.json放入ESLint在线检测工具后,得到错误提示:
2:9
Parsing error: Unexpected token
本地package.json内容
{ "name": "test", "private": true, "version": "0.0.0", "scripts": { "dev": "vite", "build": "tsc && vite build", "preview": "vite preview" }, "dependencies": { "@headlessui/react": "^1.6.6", "@react-pdf-viewer/default-layout": "^3.6.0", "@react-pdf-viewer/thumbnail": "^3.6.0", "@reduxjs/toolkit": "^1.8.5", "axios": "^0.27.2", "jsonwebtoken": "^8.5.1", "react": "^18.2.0", "react-addons-update": "^15.6.3", "react-cookie": "^4.1.1", "react-cookies": "^0.1.1", "react-dom": "^18.2.0", "react-google-recaptcha": "^2.1.0", "react-icons": "^4.4.0", "react-media-recorder": "^1.6.6", "react-multi-date-picker": "^3.3.0", "react-redux": "^8.0.2", "react-router-dom": "^6.3.0", "react-select": "^5.4.0", "react-spinners": "^0.13.3", "react-transition-group": "^4.4.5", "redux-persist": "^6.0.0", "validator": "^13.7.0" }, "devDependencies": { "@types/jsonwebtoken": "^8.5.8", "@types/react": "^18.0.0", "@types/react-addons-update": "^0.14.21", "@types/react-dom": "^18.0.0", "@types/react-google-recaptcha": "^2.1.5", "@types/validator": "^13.7.4", "@vitejs/plugin-react": "^1.3.0", "autoprefixer": "^10.4.7", "postcss": "^8.4.14", "tailwindcss": "^3.1.4", "typescript": "^4.6.3", "vite": "^2.9.9" } }
已尝试操作
- 删除
node_modules并重新执行npm install,问题未解决
排查解决步骤
- 清理文件隐藏字符与编码问题:报错提示JSON位置2存在
<符号,你提供的代码看似正常,但本地文件可能含有BOM(字节顺序标记)或不可见特殊字符。用记事本打开文件,选择「另存为」,编码选UTF-8(不带BOM)后覆盖原文件;或用VS Code打开,切换编码为UTF-8并重新保存。 - 替换为正确的package.json内容:直接复制你提供的这段无语法错误的package.json代码,覆盖本地文件,再重新执行
yarn install或npm install后启动项目。 - 移除路径中的特殊字符:项目路径包含空格(
my location),可能导致解析异常。将项目移动到不含空格、特殊字符的目录,比如C:\Projects\test。 - 清空包管理器缓存:
- npm:执行
npm cache clean --force - yarn:执行
yarn cache clean
缓存清理完成后重新安装依赖,再尝试启动项目。
- npm:执行
- 检查编辑器格式化插件:部分编辑器插件可能错误格式化JSON文件,导致语法问题。关闭可能干扰JSON格式的插件,用纯文本模式打开并保存package.json。
内容的提问来源于stack exchange,提问作者Hasan
相关产品推荐
相关产品推荐

