找不到模块:无法解决 React 中的“X”错误
Module not found: Can’t resolve ‘X’ error in React
在 React 中出现错误“Module not found: Can’t resolve”有多种原因:
- 从不正确的相对路径导入本地文件。
- 忘记安装带有
npm i somePackage
. - 使用未针对本地文件解析的扩展名(例如,不适
.js
用于 JS 文件)
要解决 React 中的“找不到模块:无法解析”错误,如果是第三方包,请确保从错误消息中安装包,例如
npm i somePackage
. 如果在导入本地文件时出现错误,请更正导入路径。
uuid
包。在项目的根目录(package.json
文件所在的位置)中打开终端并从错误消息中安装包:
# 👇️ with NPM npm install uuid # 👇️ only if you use TypeScript npm install --save-dev @types/uuid # ---------------------------------------------- # 👇️ with YARN yarn add uuid # 👇️ only if you use TypeScript yarn add @types/uuid --dev
这会将第三方包添加到项目的依赖项中。
如果错误未解决,请尝试删除您的node_modules
和
package-lock.json
(不是package.json
)文件,重新运行npm install
并重新启动您的 IDE。
# 👇️ delete node_modules and package-lock.json rm -rf node_modules rm -f package-lock.json # 👇️ clean npm cache npm cache clean --force npm install
如果在导入本地文件时出现错误,请确保更正路径并尝试使用 IDE 的自动完成功能寻求帮助。
假设我们有以下文件夹结构。
src/ components/ Button.js App.js Header.js
这就是我将Button
和Header
组件导入
App.js
文件的方式:
// 👇️ default imports import Button from './components/Button'; import Header from './Header'; // 👇️ named imports // import {Button} from './components/Button'; // import {Header} from './Header';
另一方面,如果我要将Header.js
文件导入到Button.js
文件中,我必须向上移动一个目录:
// 👇️ default imports import Header from '../Header' // 👇️ named imports // import {Header} from '../Header'
./
导入本地文件时,如果导入位于同一目录中../
的文件,或者如果导入一个或多个目录中的文件,则以导入路径开头。Delete your entire path that points to the local file, start typing and let your
IDE help you with auto-completion.
Make sure to correct any errors in the spelling, casing and path of your local
imports.
When creating local files, make sure to use an extension that is resolved by
your setup. For example, use .js
extensions for JavaScript files or make sure
your build resolves the extension you’re using.
If you use webpack, your extensions
array needs to include any extensions you
want to resolve automatically. (Simplest is to just use .js
for JavaScript
files)
module.exports = { // ... rest resolve: { extensions: [".js", ".jsx"] }, }
#
symbol, because your operating system might have issues resolving the path.For example, don’t use folder names like my-folder#3
(contains a hash #
).
If you need to install a package globally to be able to run it on the command
line from every directory, use the -g
flag.
npm i -g some-package # 👇️ this links globally installed package to local node_modules folder npm link some-package
sudo
.# 👇️ If you got permissions error, run with sudo sudo npm i -g some-package npm link some-package
The npm link command creates
a symbolic link from the globally installed package to the node_modules/
directory of the current folder.
Conclusion #
要解决 React 中的“找不到模块:无法解析”错误,如果是第三方包,请确保从错误消息中安装包,例如
npm i somePackage
. 如果在导入本地文件时出现错误,请更正导入路径。