Using reactions with requirejs

Recently, I started using reactjs along with the backbonejs router to build an application.

I usually use requirejs for dependency and code management. But the problem occurs when I try to include files containing jsx syntax.

This is what I have before my router.js :

 define(["backbone", "react"], function(Backbone, React) { var IndexComponent = React.createClass({ render : function() { return ( <div> Some Stuff goes here </div> ); } }); return Backbone.Router.extend({ routes : { "": "index" }, index : function() { React.renderComponent(<IndexComponent />, document.getElementById('index')); } }); }); 

How to put IndexComponent in your own file and call it in this file? I tried the usual method (the same one that I used with the base and reacted), but got an error due to jsx syntax.

+65
javascript reactjs requirejs frontend
Apr 30 '14 at 6:55
source share
2 answers

So, I figured it out myself.

I got the necessary files and instructions from this repo: jsx-requirejs-plugin .

As soon as I had the jsx plugin and a modified version of JSXTransformer , I changed my code according to the instructions in the repository:

 require.config({ // ... paths: { "react": "path/to/react", "JSXTransformer": "path/to/JSXTransformer", "jsx": "path/to/jsx plugin" ... } // ... }); 

Then I could reference the JSX files using the jsx! plugin jsx! . For example, to download the Timer.jsx file located in the components directory:

 require(['react', 'jsx!components/Timer'], function (React, Timer) { ... React.renderComponent(<Timer />, document.getElementById('timer')); ... }); 

I could also access .js files that had jsx syntax in them using the same code:

 require(['react', 'jsx!components/Timer'], function (React, Timer) { ... React.renderComponent(<Timer />, document.getElementById('timer')); ... }); 

In addition, I did not have to place /** @jsx React.DOM */ at the top of the files using jsx syntax.

Hope this helps.

+95
Apr 30 '14 at 9:42
source share

Response tools (including JSX) are deprecated in favor of Babel ( https://facebook.imtqy.com/react/blog/2015/06/12/deprecating-jstransform-and-react-tools.html ). I can't find a way to do this without the drag-and-drop step, so this is my grunting solution.

You can install grunt-babel (npm install grunt-babel) and configure the task as follows:

 babel: { options: { sourceMap: false, modules: "common" }, dist: { files: [{ expand: true, src: ['js/components/*.jsx'], dest: 'dist', ext:'.js' }] } } 

Just add it to your task list:

 grunt.registerTask('default', ['clean', 'copy', 'babel', 'http-server']); 

Babel converts your JSX to JS files, which can be specified as RequireJS dependencies without additional configuration.

+1
Feb 07 '17 at 8:09
source share



All Articles