After doing the React tutorial this is my index.html file:
In a project created with the create-react-app tool separating components seems to work fine like this. Define the component in a file Hello.jsx
:
import React from 'react';
var Hello = React.createClass({
render: function() {
return (
<p>Hello world!</p>
);
}
});
// Must export!
export default Hello;
And then you can import the component in another file with
import Hello from './Hello.jsx'
In my opinion ES6 can be a way to write classes and module but not really to manage them. For the purpose of managing modules I would use requirejs, simplest module manager that I know. But maybe other people will advise something else.
IMO you need a module manager and requirejs is a great tool for that.
Update: Basically for requirejs you'll write a main.js file (which is a conf file for require, defining the paths of modules and first thigns to load) In your main html you'll write something like this to load the main.js
<script data-main="scripts/main" src="scripts/require.js"></script>
Inside your views you'll call the module you need using define('MyModule'...) using the name you previously defined in the main.js (with the path).
Read the doc, don't worry this is not that terrible: http://requirejs.org/docs/start.html#add Here is a simple example: https://github.com/volojs/create-template
The way to break your code is pretty easy you'll return (this how you export a module with define()) your reactclass. Create one file for each class you have. But you can also create module/utils to gather transverse functions (parsing...etc).
Hope it helps!
If you want to create a file for each React class, I would recommend to take a look at webpack. You can develop your React classes as CommonJs modules and it will take care of bundling them together.
Also, I think it is a good option because you want to use babel to transform your jsx files. This is solved with webpack loaders.
The basic webpack configuration file would contain something like this:
webpack.config.js
var webpack = require('webpack');
module.exports = {
entry: './src/main.jsx',
output: {
// Output the bundled file.
path: './lib',
// Use the name specified in the entry key as name for the bundle file.
filename: 'main.js'
},
module: {
loaders: [
{
// Test for js or jsx files.
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel'
}
]
},
externals: {
// Don't bundle the 'react' npm package with the component.
'react': 'React'
},
resolve: {
// Include empty string '' to resolve files by their explicit extension
// (e.g. require('./somefile.ext')).
// Include '.js', '.jsx' to resolve files by these implicit extensions
// (e.g. require('underscore')).
extensions: ['', '.js', '.jsx']
}
};
I created a GitHub react-tutorial-webpack repository if you want to have actual code.