Importing from shared folder from react native

我的未来我决定 提交于 2019-12-05 18:04:16

To share code between web and native you should change how you are structuring your folders.

First start with a new project react-native init myProject this will create the default structure for RN apps.

myProject  
|  
+-- android
+-- ios
+-- index.android.js
+-- index.ios.js
...

Now create specific folders for web and shared code.

myProject  
|  
+-- android
+-- ios
+-- index.android.js
+-- index.ios.js
+-- web
+-- shared
----|------ index.js 
...

shared/index.js

function hi() {
    return 'hi';
}

module.exports = {
    hi: hi
};

index.ios.js

import { hi } from './shared/'; 

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

Here I went by this post which basically says:

Whichever folder you want to be able to import as root from, add a package.json file with { "name": "FOLDER_NAME" }. So for to achieve the same import as in the web app:

- shared  
    -- reducers  
    -- actions  
    --- todos.js
    --- package.json

Where the package.json contents is:

{
  "name": "actions"
}

Now I can do the same import as I did in the web app from my mobile app files.

EDIT

Regarding node_modules, I use the same package.json for both web and mobile. In my webpack.config I have an array of all React Native packages an these are excluded from my vendor bundle file.

Did you consider to hoist node_modules?

Moreover you can use lerna to achieve what you want instead of self-written solution.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!