找不到模块:无法解析“styled-components”[已修复]

未找到模块:无法解析 ‘styled-components’

Module not found: Can’t resolve ‘styled-components’

要解决错误“找不到模块:错误:无法解析‘styled-components’”,请确保styled-components通过在项目的根目录中打开终端并运行命令
npm install styled-components并重新启动开发服务器来安装包。

找不到模块无法解析样式组件

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

# 👇️ with NPM npm install styled-components # 👇️ ONLY If you use TypeScript npm install --save-dev @types/styled-components # ---------------------------------------------- # 👇️ with YARN yarn add styled-components # 👇️ ONLY If you use TypeScript yarn add @types/styled-components --dev

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

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

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

删除您的 node_modules 并重新安装您的依赖项

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

bash如果您使用的是 macOS 或 Linux,请在或中发出以下命令zsh

# for macOS and Linux rm -rf node_modules rm -f package-lock.json rm -f yarn.lock # 👇️ clean npm cache npm cache clean --force # 👇️ install packages npm install

如果您使用的是 Windows,请在 CMD 中发出以下命令。

命令
# for Windows rd /s /q "node_modules" del package-lock.json del -f yarn.lock # 👇️ clean npm cache npm cache clean --force # 👇️ install packages npm install

Make sure to restart your IDE and dev
server if the error persists. VS Code often glitches and a reboot solves things
sometimes.

# Verify styled-components is in your dependencies object

If you still get the error, open your package.json file and make sure it
contains the styled-components package in the dependencies object.

package.json
{ // ... rest "dependencies": { "styled-components": "^5.3.5", }, "devDependencies": { // 👇️ only if you use TypeScript "@types/styled-components": "^5.1.24" } }

The styled-components module should NOT be globally installed or be in your
project’s devDependencies. It should be in the dependencies object in your
package.json file.

You can try to manually add the lines and re-run npm install.

shell
npm install

Or install the latest version of the package:

shell
npm install styled-components@latest # 👇️ only if you use TypeScript npm install --save-dev @types/styled-components@latest

If the error persists, follow the instructions in my
Module not found: Can’t resolve ‘X’ error in React
article.