2

I have two apps (public-app and admin-app) that share some React components. Those shared components are situated in a common folder, at the root of the repository. So let's say I have:

my-app
  |__admin-app
     |__client
        |__imports
           |__Component.js
  |__public-app
  |__common
     |__SharedComponent.js

In Component.js, I try to import SharedComponent.js by doing:

import SharedComponent from '../../../common/SharedComponent'

...But it's not working, it cannot find the module.

This should be possible as it is one of the recommended approaches from the official documentation (https://guide.meteor.com/structure.html#sharing-code), so any help would be much appreciated!

mikav
  • 79
  • 1
  • 4

2 Answers2

1

If you are using babel to transpile your code, I solve this problem by using the root-import plugin. You could look this plugin to help you with requiring your files using the same syntax to point to the same folder.

With babel plugins, I would suggest looking into module-alias or babel-root-import.

module alias

With module-alias, your .babelrc would look something like this:

{
    "presets" : ["es2015", "react"],
    "plugins": [
        [
            "module-alias",
            [
                { "src": "./my-app", "expose": "my-app" },
            ]
        ]
    ],
}

..and you could then use the syntax import SharedComponent from 'my-app/common/SharedComponent'*.

root import

Or with root-import your .babelrc would be something like:

{
    "presets" : ["es2015", "react"],
    "plugins": [
        ["babel-root-import"]
    ]
}

..and you could then use the syntax `import SharedComponent from '~/my-app/common/SharedComponent'*.

*as long as you are using a babelrc file and that my-app is the root of your project.

bitten
  • 2,463
  • 2
  • 25
  • 44
-1

Meteor users: don't forget to put all your exported files in the "imports" folder, even if used through a symlink. I had an error of undefined variable because Meteor was trying to eagerly load my files put in my common folder.

So, follow @bitten advice and start by creating the symlink. Git should handle that nicely (cf. How does git handle symbolic links?): ln -s ../common/

Then, you can use https://github.com/mantrajs/babel-root-slash-import which is actually a fork from babel-root-import to simplify your import paths. (thanks @bitten).

Community
  • 1
  • 1
mikav
  • 79
  • 1
  • 4