Require JSX in React-Native

How do you need JSX in React Native?

var MyScreen = require ('./apps/screens/LoadingScreen');

The .js file is required to work, but the .jsx file was not found.

+3


source to share


4 answers


I think you just need to rename the file from .jsx to .js and the build process will take care of any conversion. Colin's answer seems to confirm this.

A JSX example in a .js file is shown at 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 .

+2


source


Here's how I ended up doing 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'],

      

open [YOU_PROJECT_FOLDER]/node_modules/react-native/packager/react-packager/src/DependencyResolver/DependencyGraph/ResolutionRequest.js

and after line 333 add these two lines:



  } else if (this._fastfs.fileExists(potentialModulePath + '.jsx')) {
    file = potentialModulePath + '.jsx';

      

This will force the packer to recognize the files mymodule.jsx

when you do something likerequire("mymodule")

Note: the actual lines are from the latest version 0.17, other versions may have different lines

+1


source


I could be wrong, but after a trawl through the source code, he looks just like js

and json

:

this._moduleExtPattern = new RegExp(
  '\.(' + ['js', 'json'].concat(this._assetExts).join('|') + ')$'
);

      

https://github.com/facebook/react-native/blob/8b93b99d4a769f86fffc95d65434f2f6a3fd827d/packager/react-packager/src/DependencyResolver/haste/DependencyGraph/index.js#L68

This issue seems to confirm this:

https://github.com/facebook/react-native/issues/231

0


source


To work with jsx files I have to add the extension jsx

to the following file

node_modules/react-native/packager/react-packager/src/node-haste/index.js

      

on line 148

extensions: extensions || ['js', 'jsx', 'json']

      

then change the file

node_modules/react-native/packager/react-packager/src/node-haste/DependencyGraph/ResolutionRequest.js

      

finally it's on line 447

} else if (this._platform != null && this._fastfs.fileExists(potentialModulePath + '.' + this._platform + '.jsx')) { file = potentialModulePath + '.' + this._platform + '.jsx';

and this is on line 457

} else if (this._fastfs.fileExists(potentialModulePath + '.jsx')) { file = potentialModulePath + '.jsx';

This solution works for latest version 0.39

0


source







All Articles