解决 Module not found: Can’t resolve ‘react-bootstrap’ 错误

要解决错误“Module not found: Error: Can’t resolve ‘react-bootstrap’”,请确保通过在项目的根目录中打开终端并运行命令 npm install react-bootstrap bootstrap 来安装 react-bootstrap 包 并重新启动我们的开发服务器。

在项目的根目录(package.json 文件所在的位置)中打开终端并运行以下命令:

#  for NPM
$ npm install react-bootstrap bootstrap

#  仅当我们使用 TypeScript
$ npm install --save-dev @types/react-bootstrap @types/bootstrap

# ----------------------------------------------

#  for YARN
$ yarn add react-bootstrap bootstrap

#  仅当我们使用 TypeScript
$ yarn add @types/react-bootstrap @types/bootstrap

该命令会将 react-bootstrap 包添加到项目的依赖项中。

如有必要,请确保重新启动开发服务器和 IDE。 在停止并重新运行 npm start 命令之前,我们的开发服务器不会接收更改。

现在应该能够在 React.js 应用程序中导入和使用 react-bootstrap 包。

App.js

import {Button, Badge} from 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';

// or
// import Button from 'react-bootstrap/Button';
// import Badge from 'react-bootstrap/Badge';

function App() {
  return (
    <div>
      <p>
        <Button variant="primary">
          Profile <Badge bg="secondary">9</Badge>
          <span className="visually-hidden">unread messages</span>
        </Button>
      </p>
    </div>
  );
}

export default App;

如果错误未解决,请尝试删除我们的 node_modules 和 package-lock.json(不是 package.json)文件,重新运行 npm install 并重新启动 IDE。

# 删除 node_modules 和 package-lock.json
$ rm -rf node_modules
$ rm -f package-lock.json

#  清除 npm 缓存
$ npm cache clean --force

$ npm install

如果错误仍然存在,请确保重新启动你的 IDE 和开发服务器。 VSCode 经常出现故障,有时重启可以解决问题。

如果仍然收到“Module not found: Error: Can’t resolve ‘react-bootstrap’”错误,请打开 package.json 文件并确保它在依赖项对象中包含 react-bootstrap 包。

{
  // ... rest
  "dependencies": {
    "bootstrap": "^5.1.3",
    "react-bootstrap": "^2.2.2",
  },

  "devDependencies": {
    "@types/bootstrap": "^5.1.9",
    "@types/react-bootstrap": "^0.32.29",
  }
}

react-bootstrap 模块不应全局安装或位于项目的 devDependencies 中,它应该位于 package.json 文件的依赖项对象中。

我们可以尝试手动添加这些行并重新运行 npm install。

$ npm install

或者安装最新版本的包:

# for NPM
$ npm install react-bootstrap@latest bootstrap@latest

# 仅当使用 TypeScript
$ npm install --save-dev @types/react-bootstrap@latest @types/bootstrap@latest