score:2

Accepted answer

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.

score:1

did you consider to hoist node_modules?

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

score:2

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/'; 

Related Query

More Query from same tag