Naoto Ida Naoto Ida - 1 month ago 18
React JSX Question

Cannot find React module when adding local npm dependency

My local custom module inside

node_modules
does not have access to the
react
package that it's parent has.

I have the following code:

// SomeComponent.js
import React, { Component } from 'react'
import {
View
} from 'react-native'
import CustomComponent from 'react-native-my-super-components'

export default SomeComponent extends Component {
render() {
return (
<View>
<CustomComponent />
</View>
)
}
}


I have a directory that has been
npm link
ed and is called
react-native-my-super-components
.

// index.js of 'react-native-my-super-components'
import React, { Component } from 'react'
import {
Text,
View,
} from 'react-native'

export default SomeComponent extends Component {
render() {
return (
<View>
<Text>SomeComponent</Text>
</View>
)
}
}


I have called
npm link react-native-my-super-component
in my project containing
SomeComponent.js
.

It's
package.json
looks like this:

{
"name": "react-native-my-super-component",
"version": "0.0.1",
"description": "My Super Component",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Naoto Ida",
"license": "MIT",
"peerDependencies": {
"react": ">=15.3.2",
"react-native": ">=0.35.0"
}
}


I don't see any differences compared to other
node_modules
. What could be causing this?

Answer

When resolving react from react-native-my-super-component, node will search in node_modules from react-native-my-super-component folder or from react-native-my-super-component parents.

You cannot have the module resolving system working the same way when using npm link.

So you can:

  • install the required missing dependency as 'dev dependency' in react-native-my-super-component folder
  • for React, that must be a singleton, you must create an alias in your webpack config file to resolve 'react' from every linked module the same way.

for example in you webpack config file, add in dev mode:

    {
        resolve: {
            alias: [
                'react': path.join(process.cwd(), 'node_modules/react')
            ]
        }
    }

This solution requires module 'path' to create an absolute path to your react module: ( import path from 'path'; ) but in you can at first try a static path.

Comments