【问题标题】:Why my React App does not fire up in browser automatically?为什么我的 React App 没有在浏览器中自动启动?
【发布时间】:2021-05-02 12:25:57
【问题描述】:

我现在正在学习 React。我使用创建应用程序

npx create-react-app .
npm start

然后我得到:

Compiled successfully!

You can now view recipe_app in the browser.

  Local:            http://localhost:3000
  On Your Network:  http://192.168.0.11:3000

Note that the development build is not optimized.
To create a production build, use npm run build.

编译工作正常,但应用程序没有在我的浏览器中自动打开(我使用的是 firefox。),所以我必须通过在浏览器中键入 URL 来手动打开它。我认为 React 应该默认启动应用程序?我不确定出了什么问题。我尝试了以下解决方案,但都不起作用。

  1. 在我的终端中使用BROWSER=firefox npm start
  2. package.json中设置BROWSER变量:
// package.json
"scripts": {
    "start": "BROWSER='firefox' react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  1. 或在scripts 中添加cross-env
// package.json
"scripts": {
    "start": "cross-env BROWSER='firefox' react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

这些解决方案都不起作用。该应用程序可以成功编译,但它只是没有在我的浏览器中打开。这是我完整的package.json 文件:

{
  "name": "recipe_app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.12.0",
    "@testing-library/react": "^11.2.6",
    "@testing-library/user-event": "^12.8.3",
    "cross-env": "^7.0.3",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "4.0.3",
    "web-vitals": "^1.1.1"
  },
  "scripts": {
    "start": "BROWSER=firefox react-scripts start",
    "chrome": "BROWSER='google-chrome' react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

我正在使用vscode 1.55.2firefox 88.0npm 6.14.11node v14.15.1Ubuntu 20.04.2 LTS。谁能帮我?谢谢!

【问题讨论】:

  • 如果您尝试从终端打开 Firefox(或 chrome),它可以工作吗? IE。你的浏览器在你的 PATH 中吗?
  • @Gregoire Lodi。你说的对!浏览器不在我的 PATH 中。我从来没有想过这个,因为我知道firefox在我的PATH中,但不知何故它不在vscode的集成终端的PATH中......我在我的系统终端中运行npm start并且没有问题。不知道为什么它在 vscode 集成终端中不起作用。

标签: node.js reactjs npm create-react-app


【解决方案1】:

我想通了。因为$DISPLAY不在vscode集成终端的环境变量中。

为了启动firefox,我需要设置export DISPLAY=:0。但这是一次性修复。

我的zsh 终端中确实有$DISPLAY,显然,vscode 没有继承它。所以我需要在setting.json文件中将inheritEnv设置为true

打开~/.config/Code/User/settings.json,然后设置:

"terminal.integrated.inheritEnv": true

然后重新启动 vscode。为确保您的修改有效,只需在终端中输入:

echo $DISPLAY
:0 // you get this

你可以走了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-29
    • 1970-01-01
    • 2016-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    相关资源
    最近更新 更多