我正在创建一个Monorepo来容纳我的React Web应用程序和我的React Native应用程序,因为它们共享许多通用代码。
我试图获得的设置是:
Project
|
+-- web
+-- native
----|------ file.js (should be able to import from 'shared/file2.js')
+-- shared
----|------ file2.js
----|------ package.json (with name="shared")
+-- package.json
从以下这篇文章开始:https ://blog.callstack.io/a-cure-for-relative-requires-in-react-native-2b263cecf0f6#.4g1o5inru我将package.json文件添加到共享文件夹中,其中:
{ "name": "shared" }
并从根文件夹中的package.json启动我的本机应用程序,如下所示:
"start-native": "./native/node_modules/react-native/packager/packager.sh"
知道我做错了什么或如何从上游的共享文件夹中导入RN应用程序中的文件吗?
EDIT:
A few details I forgot to mention.
The line giving me the error is (fake file names...):
// in native/file.js
import { aFunctionName } from 'shared/file2'
Also tried adding a name in the package.json (name=proj-root) in the root level and importing like:
import { aFunctionName } from 'proj-root/shared/file2'
Thanks!
Uri
I ended up changing the folder structure as stated in @diegopartes answer.
In addition, I wanted to achieve the effect of being able to import from the shared folder using absolute paths from both my web and mobile directories.
For this I did the following:
Web
I moved my webpack.config.js
to the root folder of the app. Inside webpack.config.js I have the following configuration the allows me to import files using absolute paths:
const path = require('path');
const sharedPath = path.join(__dirname, 'shared');
const config = {
...
resolve: {
root: [sharedPath],
},
...
}
now my shared folder acts as a root folder. Meaning, if I have
- shared
-- reducers
-- actions
--- todos.js
I can do an import { addTodo } from 'actions/todos'
Mobile
在这里,我看了这篇帖子,基本上说:
无论您想从哪个文件夹作为root导入,请使用添加package.json
文件{ "name": "FOLDER_NAME" }
。因此,为了实现与Web应用程序相同的导入:
- shared
-- reducers
-- actions
--- todos.js
--- package.json
package.json
内容在哪里:
{
"name": "actions"
}
现在,我可以从移动应用程序文件中进行与在Web应用程序中相同的导入。
编辑
关于node_modules
,我package.json
在网络和移动设备上都使用相同的代码。在我中,webpack.config
我有一个所有React Native软件包的数组,这些都从我的供应商捆绑包文件中排除了。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句