di7spider / jsx-requirejs-plugin

A RequireJS plugin for loading and compiling (with r.js) JavaScript files containing JSX.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

jsx-requirejs-plugin

A RequireJS plugin for JavaScript files containing JSX. It's r.js friendly (i.e. all files containing JSX will be pre-compiled during the r.js build).

This is helpful when using React with RequireJS.

Install

Download the plugin here.

Place this in the directory that is your baseUrl for your project, or set up a paths config for it for the module ID jsx. This plugin depends on the RequireJS text plugin to avoid reimplementation of loading logic, so it should be installed as well.

Usage

First, you need to configure RequireJS to use Facebook's JSXTransformer and React:

require.config({
  // ...

  paths: {
    "react": "react-0.8.0",
    "JSXTransformer": "JSXTransformer-0.8.0"
  }

  // ...
});

Then, you can reference JSX files via the jsx! plugin syntax. For example, to load the Timer.js file that is in a components directory:

require(['jsx!components/Timer'], function (Timer) {

});

The Plugin is then going to load the JavaScript source file components/Timer.js, parse it with Facebook's JSXTransformer and execute the resulting JavaScript source.

Build

Some specific configuration is necessary to make optimization by r.js possible.

In your build.js you should have this to remove jsx! from module names in the optimized JavaScript.

onBuildWrite: function (moduleName, path, singleContents) {
  return singleContents.replace(/jsx!/g, '');
},

To exclude jsx.js and, more importantly JSXTransformer.js due to its size, you should add "jsx" to the exclude list in the modules field of the build.js like this:

modules: [
  {
    name: "main",
    exclude: ["react", "jsx"]
  }
]

HACK to fix an issue with the preprocessing of JSXTransformer

r.js strips out all occurrences of the 'use strict' string literal causing script errors in resulting files. A simple solution to this is replacing occurrences of 'use strict' by an expression like 'use ' + 'strict'.

You don't have to do it if you use the JSXTransformer-0.8.0.js provided here.

About

A RequireJS plugin for loading and compiling (with r.js) JavaScript files containing JSX.

License:MIT License