Question

Say I have two React Components, A and B, where B depends upon (makes use of) A. Say that A is in a.js and B is in b.js .

Is there a way in React to safely resolve a dependency from B to A? Thereby guaranteeing that regardless of what order I actually include a.js and b.js, things will still resolve correctly?

I believe that the Google Closure compiler effectively fakes a dependency system for you in both development and production mode. This makes the order that different code is included in the source irrelevant; is there something like this for React?

Was it helpful?

Solution

Note: the answer below is very outdated.

I stopped using RequireJS a long time ago due to the fact that it gets rather slow in development because doesn’t bundle JS in a single file in development.

These days I’m mostly using Webpack.
You may also consider other bundlers such as Browserify and Rollup.

I use ES modules as the module system, transpiled by Babel into CommonJS. Eventually I plan to swich to ES modules completely as more bundlers with its first-class support, such as Rollup and Webpack 2, become mainstream.


Old Answer

To my knowledge, React itself doesn't provide any dependency management system; if you need one, you must use some existing tool that fits your workflow.

Personally, I'm happy using RequireJS with AMD sugar syntax so my modules look like this:

/** @jsx React.DOM */
/* jshint trailing:false, quotmark:false, newcap:false */
define(function (require) {

  'use strict';

  var React = require('react'),
      _ = require('underscore'),
      JoinWidget = require('common/views/join_widget');

  var LoginWidget = React.createClass({
    // ...
  });
});

Each React view, as any other class, gets its own file.

This is fine in development environment but I don't want to load scripts on the fly in production, so I use grunt-requirejs task with almond to concatenate files in proper order so they are always loaded synchronously in a single file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top