Reputation: 7022
How do you require JSX in React Native?
var MyScreen = require('./apps/screens/LoadingScreen');
Requiring a .js file this way works, but a .jsx file is not found.
Upvotes: 3
Views: 3378
Reputation: 4322
To work with jsx files I have to add jsx
extension to the next file
node_modules/react-native/packager/react-packager/src/node-haste/index.js
in the line 148
extensions: extensions || ['js', 'jsx', 'json']
then change file
node_modules/react-native/packager/react-packager/src/node-haste/DependencyGraph/ResolutionRequest.js
finally this in line 447
} else if (this._platform != null &&
this._fastfs.fileExists(potentialModulePath + '.' + this._platform + '.jsx')) {
file = potentialModulePath + '.' + this._platform + '.jsx';
and this in line 457
} else if (this._fastfs.fileExists(potentialModulePath + '.jsx')) {
file = potentialModulePath + '.jsx';
This solution works for latest 0.39 version
Upvotes: 0
Reputation: 409
Here's how I solved it with a quick hack:
open [YOU_PROJECT_FOLDER]/node_modules/react-native/packager/react-packager/src/DependencyResolver/DependencyGraph/index.js
and edit line 55 to look like this
extensions: extensions || ['jsx', 'js', 'json'],
the open [YOU_PROJECT_FOLDER]/node_modules/react-native/packager/react-packager/src/DependencyResolver/DependencyGraph/ResolutionRequest.js
and after line 333 add these 2 lines:
} else if (this._fastfs.fileExists(potentialModulePath + '.jsx')) {
file = potentialModulePath + '.jsx';
This will make the packager recognize mymodule.jsx
files when you do something like require("mymodule")
Note: the actual lines are from the latest 0.17 release, in other releases the lines may differ
Upvotes: 1
Reputation: 194
I think you may just have to rename your file from .jsx to .js and the build process will take care of any conversion. Colin's answer would seem to confirm this.
An example of JSX in a .js file is shown in http://moduscreate.com/react-native-has-landed/ .
The React team continues to encourage the use of JSX: http://facebook.github.io/react/docs/jsx-in-depth.html .
Upvotes: 2
Reputation: 16466
I could be wrong, but after a trawl through the source code it looks like only js
and json
are supported:
this._moduleExtPattern = new RegExp(
'\.(' + ['js', 'json'].concat(this._assetExts).join('|') + ')$'
);
This issue would seem to support that:
https://github.com/facebook/react-native/issues/231
Upvotes: 0