我创建了一个 repository其中包含一个 React 应用程序(使用 create-react-app
创建)和一个包含简单 Material UI 按钮的组件目录。文件夹结构为:
/components
/react-app
两个目录都设置为使用 Yarn 2 ,并且不在工作区中(因为我试图在单独的目录中模拟项目并简化我的真实世界场景)。
我构建组件:
$ cd ~/components && yarn build
我然后Yarn link React 应用程序的组件:
$ cd ~/react-app & yarn link ../components -r -p
这导致对
package.json
的修改react-app
中的文件目录:{
"name": "react-app",
...
"resolutions": {
"components": "portal:../components"
}
}
我的
App.tsx
文件如下所示:import './App.css';
import { Button } from 'components';
import React from 'react';
function App() {
return (
<Button>Test</Button>
);
}
export default App;
但是,当我使用
yarn start
运行 React 应用程序时我收到以下错误:./src/App.tsx
Module not found: Your application tried to access components, but it isn't declared in your dependencies; this makes the require call ambiguous and unsound.
我不确定我做错了什么。如果我在
dependencies
中添加对组件目录的显式引用(我不认为我应该这样做,因为我已经链接了它)例如:"dependencies": {
"components": "portal:../components"
}
然后我得到错误:
./src/App.tsx
Module not found: You attempted to import ~/react-app/.yarn/$$virtual/components-virtual-de9a8055ab/2/components which falls outside of the project src/ directory. Relative imports outside of src/ are not supported.
当然,我不必弹出应用程序并找到绕过此错误的方法吗?
编辑:根据 Yarn documentation “Webpack 5 将原生支持 PnP,但如果您使用 Webpack 4,则需要自己添加 pnp-webpack-plugin 插件”。在撰写本文时,
create-react-app
的最新版本依赖于 react-scripts
的 v3.4.1这又依赖于 Webpack 4。因此,我弹出了我的应用程序以检查 Webpack 配置,并且似乎已经安装了该插件。因此,这不是 CRA/Webpack 问题。我还将我的 Node 版本从 v10.16.0 升级到 v12.16.3,但无济于事。
最佳答案
TLDR;将包添加为依赖项,然后修改您的 React 设置以导入 /src
之外的文件目录。
在我的情况下,它看起来不像 yarn link
除了添加 resolutions
之外,正在做任何事情进入 package.json
,根据 documentation仅用于指定要解析的版本。也许我对 Yarn 链接的理解是错误的(尽管它在 v1 中得到了支持)。
为了解决这个问题,我必须添加对 dependencies
的引用在 package.json 中(即使我已经运行了 yarn link
):
"dependencies": {
"components": "portal:../components"
}
这导致了前面提到的
You attempted to import components which falls outside of the project src/ directory
错误。为了解决这个问题,我们要么需要退出 React 应用程序并禁用 ModuleScopePlugin
在 Webpack 中(因此允许导入 /src
文件夹之外的文件),或者使用带有 custom configuration 的 craco .我创建了 yarn-eject
和 craco
分支来证明两者。这不是一个特别优雅的解决方案,我希望有人可以发布更好的选择。我切换到 Yarn 2 以便可以使用 "Improved Peer Dependency Links"功能(因此我在我的应用程序和共享组件包中只依赖
react
的一个版本)。如果可能的话,我宁愿不必弹出我的 React 应用程序或使用自定义配置。
关于reactjs - 使用 Yarn 2 链接 React 组件时未找到模块错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61530712/