Many useful React components and React-related modules are available on NPM, and can be bundled for the client with the popular Browserify tool. We are still working on adding first-party support for using these modules to Meteor core, but there are community-maintained packages that work great!
We'll use the following community tools to load NPM packages on the client:
meteorhacks:npm
for loading NPM modules into your app: GitHub page, Atmosphere pagecosmos:browserify
for bundling NPM modules for the client using Browserify: GitHub page, Atmosphere pageYou can use these Meteor packages together to load client-side NPM modules. Here's how:
meteor add meteorhacks:npm cosmos:browserify
After you have added the packages, run your app once to let some initial setup happen. Then, you should have a file called packages.json
in the root of your app. Put any NPM packages you would like to load here. We'll use react-router
as an example, and you'll also want the externalify
package for step 4:
{
"react-router": "0.13.3",
"externalify": "0.1.0"
}
Currently, Meteor doesn't support using require
to load modules, so we will use a special file supported by cosmos:browserify
to enable this. In your app, create a file called app.browserify.js
. Inside it, you can require any of the NPM modules you loaded, and export them as "app-scope" variables, meaning they will be accessible in every JavaScript file in your app. For example, for react-router
you might do:
// In lib/app.browserify.js
ReactRouter = require("react-router");
Browserify supports numerous transforms, which let you change the way NPM packages are bundled. In particular, you will want to use the externalify
transform so that React Router uses Meteor's React package instead of one from NPM. In the same directory as the file above, create a file called lib/app.browserify.options.json
defining browserify options and transforms:
{
"transforms": {
"externalify": {
"global": true,
"external": {
"react": "React.require"
}
}
}
}
Now, you can use React Router anywhere in your app! You can use the same method to load any React component modules you find on react-components.com.
The NPM modules you require are loaded based on where your app.browserify.js
file is located. This is why we recommend putting it in lib/
, a special directory for files that need to be loaded before the rest of your app code. Read more about file load order in the Meteor docs.
This method of loading client-side NPM code works, but is not ideal in the long term. Some caveats:
require
directly in your app to request modulesWe're aware of these issues and are working on fixing them as soon as possible.