Code Monkey home page Code Monkey logo

grunt-react's Introduction

[DEPRECATED] grunt-react

Build Status Dependencies devDependencies

Grunt task for compiling Facebook React's JSX templates into JavaScript.

It also works great with grunt-browserify!


DEPRECATION NOTICE

On June 12th, 2015, the React team has deprecated JSTransform and react-tools, which this project uses:

http://facebook.github.io/react/blog/2015/06/12/deprecating-jstransform-and-react-tools.html

Please use grunt-babel instead.


Getting Started

This plugin requires Grunt ~0.4.0

If you haven't used Grunt before, be sure to check out the Getting Started guide, as it explains how to create a Gruntfile as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command:

npm install grunt-react --save-dev

Once the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript:

grunt.loadNpmTasks('grunt-react');

The "react" task

Overview

In your project's Gruntfile, add a section named react to the data object passed into grunt.initConfig().

grunt.initConfig({
  react: {
    single_file_output: {
      files: {
        'path/to/output/dir/output.js': 'path/to/jsx/templates/dir/input.jsx'
      }
    },
    combined_file_output: {
      files: {
        'path/to/output/dir/combined.js': [
          'path/to/jsx/templates/dir/input1.jsx',
          'path/to/jsx/templates/dir/input2.jsx'
        ]
      }
    },
    dynamic_mappings: {
      files: [
        {
          expand: true,
          cwd: 'path/to/jsx/templates/dir',
          src: ['**/*.jsx'],
          dest: 'path/to/output/dir',
          ext: '.js'
        }
      ]
    }
  },
})

Options

These options are passed to react-tools.

options.extension

Type: String Default value: js

Extension of files to search for JSX-syntax & convert to JS.

options.ignoreMTime

Type: Boolean Default value: false

Speed up compilation of JSX files by skipping files not modified since last pass.

options.harmony

Type: Boolean Default value: false

Turns on JS transformations such as ES6 Classes.

options.sourceMap

Type: Boolean Default value: false

Append inline source map at the end of the transformed source

Turns on JS transformations such as ES6 Classes.

options.es6module

Type: Boolean Default value: false

Allows use of ES6 module syntax. This option does not affect ES6 transformations enabled or disabled by options.harmony.


Recommended Usage

Writing your applications in CommonJS format will allow you to use Browserify to concatenate your files. Plus, with grunt-react, your templates will be converted from JSX to JS automatically!

First, install grunt-browserify to your project:

npm install grunt-browserify --save-dev

Second, register grunt-browserify in your Gruntfile:

grunt.loadNpmTasks('grunt-browserify');

Finally, add the following task to your Gruntfile:

browserify:     {
  options:      {
    transform:  [ require('grunt-react').browserify ]
  },
  app:          {
    src:        'path/to/source/main.js',
    dest:       'path/to/target/output.js'
  }
}

You've successfully concatenated your JSX & JS files into one file!


Usage Examples

Recommended Options

I recommend naming your React Components with the .jsx extension:

/**
 * @jsx React.DOM
 */

var MyComponent = React.createClass({
  ...
  render: function() {
    return (
      <p>Howdy</p>
    );
  }
});

Then, set your Gruntfile to use:

grunt.initConfig({
  react: {
    files: {
      expand: true,
      cwd: 'path/to/jsx/templates/dir',
      src: ['**/*.jsx'],
      dest: 'path/to/output/dir',
      ext: '.js'
    }
  },
})

This will output the following:

/**
 * @jsx React.DOM
 */

var MyComponent = React.createClass({displayName: 'MyComponent',
  render: function() {
    return (
      React.DOM.p(null, "Howdy")
    );
  }
});

Troubleshooting

If you encounter a file compilation error, you can run grunt --verbose to see specifics about each file being transformed.

Contributing

In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using Grunt.

Release History

  • v0.12.2

    • Move verbose logging to grunt --verbose (#53)
  • v0.12.1

    • Fix issue with Browserify (#46)
  • v0.12.0

    • Update all dependencies & devDependencies
  • v0.11.0

    • Update react-tools to v0.13.0 (#45)
  • v0.10.0

  • v0.9.0

    • Continue compilation despite error. (#31)
  • v0.8.4

    • Add support for harmony via additional options. (#32)
  • v0.8.3

    • Update to react-tools at ^v0.11.0 (#33)
  • v0.8.2

    • Emit react.error for Growl & other notifications (#23)
  • v0.8.1

    • Throw a proper error when React fails (#25)
  • v0.8.0

    • Update to React v0.10.0 (#27)
  • v0.7.0

    • Update to React v0.9.0 (#24)
  • v0.6.0

    • Task changes to allow for flexible file options as found in the grunt-contrib-* projects.
    • Taking hints from grunt-contrib-less to allow for compiling single files separately, dynamic mappings and combining.
    • Removed extension option as this is determined by flexible file matching now.
    • Removed MT time ignoring, this can be easily done with the grunt-newer plugin.
    • Errors are ignored and skipped by default to match how other grunt plugins work.
  • v0.5.2

    • grunt.fail instead of throwing an error (#11)
  • v0.5.1

    • Add file name to errors (#15)
  • v0.5.0

    • Update to react-tools ~v0.5.0
  • v0.4.1

    • Add logging to make it easier catch errors, thanks to @lorefnon (#5)
  • v0.4.0

    • Update to react-tools ~0.4.0, thanks to @Agent-H (#3)
  • v0.3.0

    • No longer uses bin/jsx, thanks to @petehunt (#2)
  • Add ignoreMTime option

  • v0.2.0

    • Add require('grunt-react').browserify() and require('grunt-react').source() for compiling within Node
  • v0.1.0

    • Initial release

Bitdeli Badge

grunt-react's People

Contributors

ammit avatar apendua avatar asponring avatar bitdeli-chef avatar brutaldev avatar danielhasselrot avatar ericclemmons avatar glittershark avatar gsouf avatar hmil avatar icodeforlove avatar ivanzhaowy avatar jgebhardt avatar magalhas avatar mrjoes avatar petehunt avatar steida avatar tleruitte avatar vegetabill avatar vkramskikh avatar wincent avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

grunt-react's Issues

How to pass in options into browserify transform?

Currently, I have a config as shown below. Is the ignoreMTime property placed in the correct place for browserify to read it as a valid option for the transform?

browserify: {
            options: {
                transform: [[gruntReact.browserify, {ignoreMTime: true}], configify, nwjsify],
                browserifyOptions: {
                    debug: true // source mapping
                }
            },
            dev: {
                src: ['asr/*.jsx', 'asr/**/*.jsx', 'asr/**/*.js'],
                dest: 'public/js/compiled/bundle.js',
                options: {
                    watch: true, // use watchify for incremental builds!
                    keepAlive: true // watchify will exit unless task is kept alive
                }
            },
            prod: {
                src: ['asr/*.jsx', 'asr/**/*.jsx', 'asr/**/*.js'],
                dest: 'public/js/compiled/bundle.js'
            }
        },

delegate options to transform call

As the title says. The options parameter just takes the harmony flag for now, but it may take other options in the future. I'm going to open a PR for this.

Handling multiple JSX compile targets that source from any location in the project

I have a situation like this where I want to set up specific destination targets for different types of React Component files in my application:

react: {

  // Components
  components: {
    expand: true,
    cwd: './',
    ext: '.js',
    src: [
      'app/modules/components/**/*.js',
      'app/modules/components/**/*.jsx',
      'bower_components/widget-library/src/components/**/*.js',
      'bower_components/widget-library/src/components/**/*.jsx',
      '!app/modules/components/**/*-test.js',
      '!bower_components/widget-library/src/components/**/*-test.js'
    ],
    dest: 'serve/modules/components'
  },

  // Widgets
  widgets: {
    expand: true,
    cwd: './',
    ext: '.js',
    src: [
      'app/modules/widgets/**/*.js',
      'app/modules/widgets/**/*.jsx',
      'bower_components/widget-library/src/widgets/**/*.js',
      'bower_components/widget-library/src/widgets/**/*.jsx',
      '!app/modules/widgets/**/*-test.js',
      '!bower_components/widget-library/src/widgets/**/*-test.js'
    ],
    dest: 'serve/modules/widgets'
  }
}

What ends up happening, however is the relative pathing for all of these src targets specified are preserved in the dest location's output:

image

Is there any way to force grunt-react to flatten these out so that no matter where src files are specified (they could be a bower component, npm module or just a commited source file in the project) they are placed in the directory specified by the dest property without their relative pathing (e.g. 'bower_components/etc/etc')?

grunt-react not work on react 0.13.3

It will show error: "Invariant Violation: React.render(): Invalid component element. This may be caused by unintentionally loading two independent copies of React."

app.built.js

This is more of a question then an issue. I'm new to both Hapi and React but I'm curious why the app.built.js is so large. It looks like grunt is calling browserify on the src/react_components/ directory but the app.built.js has a lot of other stuff in it. Is this common? Is all of the extra stuff just React?

Does not work on windows ?

Has grunt-react been tested to work on windows ?

While I have been successfully using it on linux, I recently needed to use it in windows and the jsx files are being copied as it is, without being compiled.

How to use grunt-react with grunt-browserify?

Hi,

I would like to use grunt-react together with grunt-browserify. I've tried to follow your instructions, but the require('grunt-react').browserify always returns null. My Gruntfile.js looks like this.

module.exports = function (grunt) {
    grunt.initConfig({
        browserify: {
            app: {
                files: {
                    "wwwroot/js/app.js": ["Scripts/App.js"]
                },
                options: {
                    transform: [require('grunt-react').browserify]
                }
            }
        },
        browserifyBower: {
            lib: {
                options: {
                    file: "wwwroot/lib.js",
                    checkVersions: false
                }
            }
        },
        bower: {
            install: {
                options: {
                    layout: "byComponent",
                    targetDir: "wwwroot/lib",
                    cleanTargetDir: false
                }
            }
        }
    });

    grunt.loadNpmTasks("grunt-browserify");
    grunt.loadNpmTasks("grunt-browserify-bower");
    grunt.loadNpmTasks("grunt-bower-task");

    grunt.registerTask("default", [
        "bower:install",
        "browserify"
    ]);
};

Did I miss something?

Thank you!

In version 0.6.0, source filenames get truncated after the first period/dot

I hope to submit a patch for this after investigation, but I'm not going to get to it tonight.

I just tried to upgrade, and had to revert to the 0.5.x version. I have JavaScript files with names like:
require-0.2.9.1.js, and when the grunt-react 0.6.0 processes that file, it renames it to require-0.js

Support logging of file names

When a file fails to compile, only line number and nature of error is reported and no information is provided as to which file failed to compile.

Cannot transfer props using JSX destructuring assignment

I'm using grunt-react v0.10.0 with Browserify and if fails to parse the new JSX way of selectively transferring props using destructuring assignment. Basically adding this line inside my component's render function...

var { checked, ...other } = this.props;

...results in this error:

Error: Parsing file /path/to/my/component/MyComponent.jsx: Line 26: Unexpected token ...

EDIT:
So I assume is to do with not having harmony=true set. How do I enable this when used with Browserify?

class → className

I tried to use grunt-react with the 0.5.1 build of react.js. The react team decided that the property className should be used to add the class attribute to elements (instead of just class). Unfortunately grunt-react compiles to class, e.g.

<div class="test"></div>

compiles to

React.DOM.div( {class:"test"});

but it should be

React.DOM.div( {className:"test"});

That might not be a problem in grunt-react but in react-tools. I just wanted to open this issue, in case someone has the same problems while using grunt-react.

Individual output folders

Here's my grunt config:

react: {
  options: {
    extension: 'jsx',
    ignoreMTime: false
  },
  apps: {
    files: {
      'public/apps/': ['public/apps/']
    }
  }
}

This would take public/apps/foo/bar.jsx and turn it into public/apps/foo/bar.js. Is there a way I could instead move it into something like public/apps/foo/build/bar.js? I'd like to be able to ignore the built files from jshint, since they fail with my current project's rules.

I don't have a central location where all my React files live, and I'd rather not put grunt rules for ever folder that does (could be dozens).

Publish new version to npm

The README explains the project is deprecated, but the module page on npm doesn't have this info as it wasn't pushed.

Could you push a new version to npm so users there know to use grunt-babel? Thanks!

File concatenation not idempotent (i.e. different results after multiple times with same input)

Hi,
We're a development team using grunt-react (which is awesome!) for compiling JSX to JS. We've recently enabled the file concatenation/combination feature and it works good, but we've got some problems that it seems to combine the files differently for different developers? We're all using version ~0.9.0, and for technical reasons we're still bound to checking in both our JSX and JS files into version control.

After someone has made a change in the JSX file, compiled it into JS, committed and pushed — then someone else pulls down the code, grunt watch detects and recompiles the JS files again — now with different output. Why?

Here's an example from what "git diff" says has changed:

@@ -1134,7 +1134,7 @@ define('components/header__menu', ['react', 'utils', 'components/header__languag
     });

     return MobileMenu;
-});
+});
 /**
  * @jsx React.DOM
  */

As you might've guessed, that place is the end+beginning of 2 different files that are concatenated.

How require component with .jsx extension?

I had a problem.

When I try require a component without extension:

var Item = require('./Item');

In the console throws out an error:

Error: Cannot find module './Item' from '/Users/kulakowka/Documents/node.js/geekhub/assets/jsx'

But if I try to require a component with extension:

var Item = require('./Item.jsx');

It works!

Task configuration looks like this:

grunt.config.set('browserify', {
    options:      {
      transform:  [ require('grunt-react').browserify ]
    },
    dev:          {
      src:        'assets/jsx/app.jsx',
      dest:       '.tmp/public/js/app.js'
    }
  });
  grunt.loadNpmTasks('grunt-browserify');

I tried to add the extension option:

grunt.config.set('browserify', {
    options:      {
      transform:  [ require('grunt-react').browserify ],
      extension: 'jsx'
    },
    dev:          {
      src:        'assets/jsx/app.jsx',
      dest:       '.tmp/public/js/app.js'
    }
  });
  grunt.loadNpmTasks('grunt-browserify');

But it did not help.

I would use .jsx extension for files with components. But I am sure that indicate the file extension in the require () is not required. Maybe it's a bug?

Optional Chaining and Numerical Coalescing Operator.

Hello! I love using this library and would also love if you could support the New ES11 Optional Chaining and the Numerical Coalescing Operator.

Optional Chaining:

const myObj = {
  foo: {
    bar: "hello"
  }
};
console.log(myObj.foo?.baz);
//This allows me to still use a deeply nested variable in an object without returning undefined.

Numerical Coalescing Operator:

const foo = undefined;
const bar = foo ?? "hey";
//By using the Numerical Coalescing Operator I can return bar as the string if foo is undefined or null

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.