为什么我的 React App 没有在浏览器中自动启动?

Why my React App does not fire up in browser automatically?

我正在学习 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 应该默认启动应用程序?我不确定哪里出了问题。我尝试了以下解决方案,但其中 none 有效。

  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
  2. 中添加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"
  },

None 这些解决方案有效。该应用程序可以成功编译,但它只是无法在我的浏览器中打开。这是我的完整 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。谁能帮我?谢谢!

我明白了。这是因为$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

一切顺利。