Giter Club home page Giter Club logo

reactify's Introduction

reactify

DEPRECATED: Use babelify instead (make sure you configured Babel with babel-preset-react).

Browserify transform for JSX (superset of JavaScript used in React library):

var React = require('react')

class Hello extends React.Component {

  render() {
    return <div>Hello, {this.props.name}!</div>
  }
}

Save the snippet above as main.js and then produce a bundle with the following command:

% browserify -t reactify main.js

reactify transform activates for files with either .js or .jsx extensions.

If you want to reactify modules with other extensions, pass an -x / --extension option:

% browserify -t coffeeify -t [ reactify --extension coffee ] main.coffee

If you don't want to specify extension, just pass --everything option:

% browserify -t coffeeify -t [ reactify --everything ] main.coffee

ES6 transformation

reactify transform also can compile a limited set of es6 syntax constructs into es5. Supported features are arrow functions, rest params, templates, object short notation and classes. You can activate this via --es6 or --harmony boolean option:

% browserify -t [ reactify --es6 ] main.js

es6 class getter and setter methods can be activated via --target es5 option:

% browserify -t [ reactify --es6 --target es5 ] main.js

You can also configure it in package.json

{
    "name": "my-package",
    "browserify": {
        "transform": [
            ["reactify", {"es6": true}]
        ]
    }
}

Troubleshooting

Code in 3rd-party packages isn't being transformed by reactify

By default Browserify applies transforms only for modules in the current package. That means that if there are modules with JSX in packages in node_modules/ directory then browserify will throw SyntaxError left and right even if you are using reactify.

The best way to fix that is ask package author to publish to npm with code compiled down to plain ES5 which is runnable in browsers and Node.js as-is.

Another approach is to ask to add

"browserify": {
  "transform": ["reactify"]
}

to the package's package.json. That will make Browserify apply reactify transform for that package too.

Another way is to activate reactify with -g option which will instruct Browserify to apply reactify to every module it encounters:

% browserify -g reactify main.js

Note that this will lead to slower builds as every module will be parsed and transformed by reactify even if it doesn't have JSX code in it.

reactify's People

Contributors

andreypopp avatar brigand avatar djebbz avatar gisborne avatar gregerolsson avatar luigy avatar markdalgleish avatar misumirize avatar petehunt avatar piranha avatar uggedal 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  avatar  avatar  avatar  avatar  avatar

reactify's Issues

jstransform failed

Test file hi.js:

/** @jsx React.DOM */
'use strict';
var React = require('react');
var Foo = React.createClass({
  getInitialState: () => ({}),
  render: () => <div />,
});
$ browserify  -t [ reactify --es6 ] hi.js
Error: Parsing file /tmp/hi.js: Line 5: Unexpected token )

react-tools v0.10 supports --harmony flag which also uses jstransform. It can deal with the test file correctly:

$ jsx --harmony < hi.js
built Module("<stdin>")
/** @jsx React.DOM */
'use strict';
var React = require('react');
var Foo = React.createClass({displayName: 'Foo',
  getInitialState: function()  {return {};}),
  render: function()  {return React.DOM.div(null );},
});

Is there any plan to default to that instead?

Consider Deprecating in favor of babelify

I have used this a bit to help with JSX and ES6 transpiling, and thank you very much for this project.

In recent research on other common utilities, node-jsx for example, it seems like a better option to use https://github.com/babel/babelify instead of reactify.

Unless reactify has some additional features specific to JSX + ES transpiling I am missing.

Thank you for your work, either way this module has been really helpful.

Source maps include full local path names, not shown in original folders

When I bundle with this command - watchify main.js -t reactify -o bundle.js -v -d the source file names appear in devtools with the file name including the full local file path and they are not shown in their nested folders.

This causes a few problems with many files as it is hard to see which file you are looking at.

I have posted a SO question which includes some screenshots that might help explain what I mean.

Is there a solution to this or am I doing something wrong?
Thanks
(If cross posting or linking etc. is frowned upon let me know and I will remedy- i am new to issues on github)

Use jstransform directly instead of react-tools

I'm going to kill off react-tools. We haven't made a lot of noise about it but I will soon. I already shipped an updated version of jstranform with an API that is very similar to react-tools so the switch should be pretty easy. I even wrote a migration guide. This let's us ship transforms faster and not block on React releases.

It would be great if reactify could upgrade :)

Adding {stripTypes: true} flag to the transform causes an error with type.js

Context

OS: OS X 10.9.5

gulpfile.js

var gulp = require('gulp'),
    del = require('del'),
    autoprefixer = require('gulp-autoprefixer'),
    rename = require('gulp-rename'),
    minifycss = require('gulp-minify-css'),
    concat = require('gulp-concat'),
    browserify = require('browserify'),
    uglify = require('gulp-uglify'),
    sass = require('gulp-ruby-sass'),
    bower = require('gulp-bower'),
    express = require('express'),
    tinylr = require('tiny-lr')(),
    connectlr = require('connect-livereload')
    reactify = require('reactify');

gulp.task('scripts', function() {
    var bundler = browserify();

    return bundler
        .add('./src/scripts/main.js')
        .transform(reactify, {stripTypes: true})
        .bundle()
        .pipe(gulp.dest('dist/assets/js'))
        // Minification
        .pipe(rename({suffix: '.min'}))
        .pipe(uglify())
        .pipe(gulp.dest('dist/assets/js'));
});

package.json (dev-dependancies)

  "devDependencies": {
    "bower": "^1.3.12",
    "browserify": "^6.3.2",
    "connect-livereload": "^0.5.0",
    "del": "^0.1.3",
    "express": "^4.10.1",
    "gulp": "^3.8.10",
    "gulp-autoprefixer": "^1.0.1",
    "gulp-bower": "0.0.7",
    "gulp-concat": "^2.4.1",
    "gulp-flowtype": "^0.3.0",
    "gulp-minify-css": "^0.3.11",
    "gulp-rename": "^1.2.0",
    "gulp-ruby-sass": "^0.7.1",
    "gulp-uglify": "^1.0.1",
    "path": "^0.4.9",
    "reactify": "^0.17.1",
    "tiny-lr": "^0.1.4"
  }

Resulting Error

[13:32:48] Using gulpfile ~/WebstormProjects/vinnyr-animation/gulpfile.js
[13:32:48] Starting 'scripts'...

path.js:313
        throw new TypeError('Arguments to path.resolve must be strings');
        ^
TypeError: Arguments to path.resolve must be strings
    at Object.exports.resolve (path.js:313:15)
    at DestroyableTransform.saveFile [as _transform] (/Users/vincentriemer/WebstormProjects/vinnyr-animation/node_modules/gulp/node_modules/vinyl-fs/lib/dest/index.js:36:26)
    at DestroyableTransform.Transform._read (/Users/vincentriemer/WebstormProjects/vinnyr-animation/node_modules/gulp/node_modules/vinyl-fs/node_modules/through2/node_modules/readable-stream/lib/_stream_transform.js:184:10)
    at DestroyableTransform.Transform._write (/Users/vincentriemer/WebstormProjects/vinnyr-animation/node_modules/gulp/node_modules/vinyl-fs/node_modules/through2/node_modules/readable-stream/lib/_stream_transform.js:172:12)
    at doWrite (/Users/vincentriemer/WebstormProjects/vinnyr-animation/node_modules/gulp/node_modules/vinyl-fs/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:237:10)
    at writeOrBuffer (/Users/vincentriemer/WebstormProjects/vinnyr-animation/node_modules/gulp/node_modules/vinyl-fs/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:227:5)
    at DestroyableTransform.Writable.write (/Users/vincentriemer/WebstormProjects/vinnyr-animation/node_modules/gulp/node_modules/vinyl-fs/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:194:11)
    at Labeled.ondata (/Users/vincentriemer/WebstormProjects/vinnyr-animation/node_modules/browserify/node_modules/labeled-stream-splicer/node_modules/stream-splicer/node_modules/readable-stream/lib/_stream_readable.js:572:20)
    at Labeled.emit (events.js:95:17)
    at readableAddChunk (/Users/vincentriemer/WebstormProjects/vinnyr-animation/node_modules/browserify/node_modules/labeled-stream-splicer/node_modules/stream-splicer/node_modules/readable-stream/lib/_stream_readable.js:195:16)

Additional Comments

If I remove the {stripTypes: true} from the transform statement it seems like the gulp task runs fine (except I get a different error because I have type annotations which confuses Browserify)

npm install fails due to grunt peerDependencies

When trying to install reactify I get the following error.

npm install reactify

npm ERR! Darwin 14.0.0
npm ERR! argv "node" "/Users/aran/.nvm/v0.10.32/bin/npm" "install" "reactify" "--save"
npm ERR! node v0.10.32
npm ERR! npm  v2.1.10
npm ERR! code EPEERINVALID

npm ERR! peerinvalid The package grunt does not satisfy its siblings' peerDependencies requirements!
npm ERR! peerinvalid Peer [email protected] wants grunt@~0.4.0
npm ERR! peerinvalid Peer [email protected] wants grunt@~0.4.0
npm ERR! peerinvalid Peer [email protected] wants grunt@>= 0.4.0 < 0.5
npm ERR! peerinvalid Peer [email protected] wants grunt@~0.4.0
npm ERR! peerinvalid Peer [email protected] wants grunt@~0.4.2

npm ERR! Please include the following file with any support request:

Also has lots and lots of unmet dependency warnings!

"Unexpected token" error when running Reactify

Hi, I've done my best to work around this issue but cannot find the error in my approach.

I'm trying to setup Reactify using various iterations of the following code (in my gulpfile.js):

var browserify = require('browserify');
var watchify = require('watchify');
var source = require('vinyl-source-stream');
var reactify = require('reactify');

function scripts(watch) {
  var bundler, rebundle;

  bundler = browserify(config.paths.main, {
    basedir: __dirname,
    //debug: !config.production,
    debug: false,
    cache: {}, // required for watchify
    packageCache: {}, // required for watchify
    fullPaths: watch // required to be true only for watchify
  });

  if (watch) {
    bundler = watchify(bundler);
  }

  rebundle = function () {
    return bundler
      .transform(reactify)
      .bundle()
      .pipe(source('index.js'))
      .pipe(gulp.dest('./dist'));
  };

  bundler
    .on('update', rebundle)
    .on('error', function (e) {
      gutil.log('Browserify error', e);
      this.emit('end');
    });

  return rebundle();
}

gulp.task('scripts', ['clean-js'], function () {
  return scripts(false);
});

gulp.task('watch-scripts', ['clean-js'], function () {
  return scripts(true);
});

Running gulp scripts produces the error Unexpected token pointing to the beggining of a JSX in this file:

/** @jsx React.DOM */
var React = require('react');

module.exports = React.createClass({
  render: function () {
    return (
      <h1>Test</h1>
    );
  }
});

Versions:

Is there something obvious I'm missing? Would love any help, thanks!

browserify-generated sourcemap contains output from JSX instead of input

browserify has a debug option to generate a sourcemap. However, when used with reactify, the sourcemap contains the output from JSX, not the input. When you view a source file using Chrome's debugger, the file will appear to contain the wrong content. This can be rather confusing since it looks like the original source file was overwritten.

It seems like reactify should work with browserify to merge the sourcemap from JSX with the sourcemap from browserify.

Reactify is not able to handle import/export declarations, even with Harmony tag (Fix inside)

Heya. I've been tinkering around with reactify and ES6 for a little while now, and have been blocked by the errors: Illegal export declaration while parsing file and Illegal import declaration while parsing file.

After some digging, I found that React's JSX Transformer, used by react-tools, does not appear to parse import or export declarations unless you explicitly set a certain flag. Not the harmony flag. For some reason, this flag is currently undocumented. The important flag here is es6module, and it can be found being used in React's JSXTransformer. https://github.com/facebook/react/blob/master/docs/js/JSXTransformer.js

Specifically, take a look at line #8746: https://github.com/facebook/react/blob/master/docs/js/JSXTransformer.js#L8746

var isModule = extra.sourceType === 'module' || extra.sourceType === 'nonStrictModule';

        if (isModule && lookahead.type === Token.Keyword) {
            switch (lookahead.value) {
            case 'export':
                return parseExportDeclaration();
            case 'import':
                return parseImportDeclaration();
            }
        }

While I'm still looking into the code, and may not be fully aware of all the implications of this flag, it does appear that, without this flag (or nonStrictEs6Module), it will not parse import or export declarations, leading to the troublesome error I've been getting.

Right now, I've set the es6module flag to be turned on manually in reactify, though an official configuration for this would be appreciated. Cheers!

Reactify doesn't convert JSX to JS for modules in node_modules

Hi,

I'm using reactify, and tried the following with versions 0.11.0, 0.12.0, 0.13.0, 0.13.1, 0.14.0 and Browserify 3.31.2, 4.2.3, 5.13.1 and 6.2. Almost all combinations have been tested, but mostly reactify 0.14.0 with all aforementioned versions of Browserify.

The problem : I've developped a React component that is common to several sites, so I decided to share it by publishing it to our internal GitLab. The module ends up in /node_modules. Since then, either compilation fails because of a Parse Error, of it fails silently and the JSX of the component isn't transformed in the end. Before sharing it (and therefore putting the module into node_modules), the exact same code was in my local hierarchy of folder and it worked perfectly fine.

Steps to reproduce

I've managed to create a minimal test case that exhibits the problem.

toto.js // Main file for my test
package.json // Contains alias to the browserify build command
node_modules/
--  toto/  // React component shared
------  index.js // Entry point
------  package.json // Contains the react dependency only

toto.js :

var toto = require("toto");

package.json :

"scripts": {
  "toto": "browserify -t reactify toto.js -o toto-out.js"
},
"dependencies": {
  "browserify": "6.2.0",
  "reactify": "https://github.com/andreypopp/reactify/archive/v0.14.0.tar.gz"
}

node_modules/toto/index.js :

/** @jsx React.DOM */
"use strict";

var React = require("react");

var Toto = React.CreateClass({
    render: function() {
        return ( <h1>TOTO</h1> );
    }
});

node_modules/toto/package.json :

{
  "name": "toto",
  "version": "0.0.0",
  "main": "index.js",
  "dependencies": {
    "envify": "~1.2.1",
    "react": "~0.9.0"
  }
}

Case 1 : compilation fails

The error happens with Browserify 3.31.2. When I type npm run toto, the following error happens :

╰─$ npm run toto

> [email protected] toto /SOME/PATH/
> browserify -t reactify toto.js -o toto-out.js

Error: Parsing file /SOME/PATH/node_modules/toto/index.js: Line 8: Unexpected token <

npm ERR! [email protected] toto: `browserify -t reactify toto.js -o toto-out.js`
npm ERR! Exit status 1
...

The line 8 corresponds to the first occurence (and only here) of JSX in the React component (<h1>TOTO</h1>).

Case 2 : compilation fails silenlty

This happens with any version of Browserify >= 4, even the latest 6.2.0. npm run toto exits succesfully, but the JSX isn't compiled at all so the code fails in the browser with a syntax error. In toto-out.js I can see it :

},{}],2:[function(require,module,exports){
/** @jsx React.DOM */
"use strict";

var React = require("react");

var Toto = React.CreateClass({
    render: function() {
        return ( <h1>TOTO</h1> );
    }
});

},{"react":132}],3:[function(require,module,exports){

** Hints **

The error message comes from module-deps. It's supposed to execute any transform before parsing the file, as explained here. In case 1, it's like the transform isn't executed at all or registered to execute after parsing, hence the error. In case 2, it's like it's executed but not written to disk, not sure exactly. I tried debugging but I don't have time to dive into the Browserify stack in details, and I'm not sure where to start. My temporary workaround will be to transform the JSX upfront so that I require a normal JS file.

I hope the report was detailed enough so you can have a look. I'm not even sure it's related to reactify or module-deps. If I'm wrong I'd be happy to recreate the issue in the appropriate location.

Doesn't work if main file uses JSX syntax

I have a very small React app using Browserify and Reactify. The "main.js" is like this :

var myComponent = require('./components/mycomponent'),
    React = require('react-tools').React;

React.renderComponent(
    myComponent({}),    
    document.getElementById('whatever')
);

With this code, browserify -t reactify main.js -o bundle.js works. If I change the call to renderComponent to use JSX syntax instead, like :

React.renderComponent(
    <myComponent />,    
    document.getElementById('whatever')
);

The build command fails with this error : Error: Parsing file d:\playground\sprint_0\src\main\js\src\react-app.js: Line 5: Unexpected token <. Note that I also tried replacing the -t reactify with the browserify.transform entry in the package.json. Same.

The component itself uses JSX syntax and requires other files that uses JSX syntax, this causes no problem.

upgrade path for visitors option?

Running browserify with reactify, I get the error

option "visitors" is deprecated and will be removed in future releases

What's the upgrade path for this? What option should I be using?

Unexpected identifier

Hi,
I am getting this error:

ReactifyError: /.../..../settings.js: Pa rse Error: Line 54: Unexpected identifier while parsing file:

while trying parsing this line:

<input type="checkbox" ref='opt' {isChecked} />

if I delete the {isChecked} but I can see why this is an error

typo in error message

ReactifyError: C:\Users\Mike\Documents\Git projects\collaborations\mofo-example-app\react\LogoType.jsx:
Parse Error: Line 9: Expected corresponding XJS closing tag for img while parsing file:
C:\Users\Mike\Documents\Git projects\collaborations\mofo-example-app\react\LogoType.jsx

That XJS should probably be JSX =)

String is not being escaped properly with harmony string interpolation feature.

I was hoping to use the string interpolation features of harmony but I'm running into an error when using the flag --harmony with reactify.

I first run npm start an all is well. As soon as I hit the code in the module (listed below) I get the error shown here. I'm not sure if this is an issue with reactify or not.

error

Error: Invalid URI "http:/localhost:8002/login" {stack: (...), message: "Invalid URI "http:/localhost:8002/login""}

config file

{
  "server": {
    "uri": "http://localhost",
    "port": "8002"
  }
}

module

var config = require('../../config.json');
// ...

module.exports = {
  login: function(username, password) {
    request.post(path.join(`${config.server.uri}:${config.server.port}`, 'login'), {
        username: username,
        password: password
      }, function(err, httpRes, body) {
        if (err) {
          return console.error(err);
        }
        ServerActionCreators.receiveLoginResult(httpResp);
      }
    );
  }
};

package.json

{
scripts: {
    start: watchify -t [ reactify --harmony ] -o js/bundle.js -v -d . & http-server -p 8002,
    build: NODE_ENV=production browserify -t [ reactify --harmony ] . | uglifyjs -cm > js/bundle.min.js,
    test: jest
  }
}

v 0.17.1 Unexpected token

/* package.json */
{
  "scripts": {
    "watch": "watchify src/app.js -o public/js/scripts.js",
    "build": "browserify src/app.js -o public/js/scripts.js",
  },
  "dependencies": {   
    "react": "~0.12"
  },
  "devDependencies": {
    "browserify": "~6.0.3",
    "reactify": "~0.17",
    "watchify": "~2.1",
  },
  "browserify": {
    "transform": [ "reactify" ]
  }
}
// src/app.js
/** @jsx React.DOM */

var React = require('react'),
    Form = require('app/component/form.react');

var initial = { number: 25 };

React.render( <Form init={initial} /> , '#mount-point');
// src/component/form.react.js
/** @jsx React.DOM */

var React = require('react');

//noinspection JSUnusedGlobalSymbols
module.exports = Form = React.createClass({
    getInitialState: function() {
        return this.props.init;
    },
    onInputChange: function(ev) {
        console.log(ev);
    },
    render: function() {
        return (
            <form method="post">
                <label htmlFor="number">
                    <input
                        name="number"
                        id="number"
                        type="text"
                        value={this.state.number}
                        onChange={this.onInputChange}/>
                </label>
            </form>
        );
    }
});

Note: i have a symlink src/ dir to node_modules/app
always i get Error: Parsing file /home/rkmax/Development/project/src/component/form.react.js: Unexpected token (15:12)

Reactify with coffeeify doesn't work

Hello,

I can't seem to get reactify to work with coffeeify. I followed the readme to no avail.

app.coffee

### @jsx React.DOM ###

console.log 'hi'

browser command:

browserify -t coffeeify -t [ reactify -x coffee] ./src/coffeescripts/app.coffee                                               
/Users/mueller.128/repos/klc/react_colorpicker/src/coffeescripts/app.coffee:1
/** @jsx React.DOM */
^
ParseError: regular expressions cannot begin with `*`

my attempt at using the browserify api in a gulp task

var browserify = require('browserify');
var source     = require('vinyl-source-stream');
var watchify   = require('watchify');
var coffeeify  = require('coffeeify');
var reactify   = require('reactify');


gulp.task('browserify', function() {
  return browserify('./src/coffeescripts/app.coffee')
    .transform({ }, coffeeify)
    .transform({ extension: "coffee" }, reactify)
    .bundle({debug: true})
    .pipe(source('./src/bundle.js'))
    .pipe(gulp.dest('./build/javascripts/'));
});

Thanks for any help.

Source map become bigger and bigger (with watchify)

For an empty index.js , the source map (extracted by exorcist) of first build is 1007 bytes,
the source map of second rebuild become 1563 bytes,
third rebuild become 12,655, and quickly becomes few megabytes.
it seems like "sourcesContent" is including itself recursively.

This happen only in 1.0.0, 0.17.1 is fine.
my browserify/watchify setting
{ cache: {}, packageCache: {}, fullPaths: true, debug:true, builtins: false, commondir: false, detectGlobals: false}

///////////////// first build//////////////////
"mappings": "AAAA;ACAA;AACA",
"file": "generated.js",
"sourceRoot": "",
"sourcesContent": [
"(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})",
"\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidHJhbnNmb3JtZWQuanMiLCJzb3VyY2VzIjpbIkM6XFwyMDE1XFx0ZXN0bWFwXFxpbmRleC5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiIiwic291cmNlc0NvbnRlbnQiOlsiIl19"
]

///////////////////second build////////////////
"mappings": "AAAA;ACAA;AACA,0NAA0N;AAC1N",
"file": "generated.js",
"sourceRoot": "",
"sourcesContent": [
"(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})",
"\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidHJhbnNmb3JtZWQuanMiLCJzb3VyY2VzIjpbIkM6XFwyMDE1XFx0ZXN0bWFwXFxpbmRleC5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiIiwic291cmNlc0NvbnRlbnQiOlsiIl19\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidHJhbnNmb3JtZWQuanMiLCJzb3VyY2VzIjpbIkM6XFwyMDE1XFx0ZXN0bWFwXFxpbmRleC5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTtBQUNBIiwic291cmNlc0NvbnRlbnQiOlsiXG4vLyMgc291cmNlTWFwcGluZ1VSTD1kYXRhOmFwcGxpY2F0aW9uL2pzb247YmFzZTY0LGV5SjJaWEp6YVc5dUlqb3pMQ0ptYVd4bElqb2lkSEpoYm5ObWIzSnRaV1F1YW5NaUxDSnpiM1Z5WTJWeklqcGJJa002WEZ3eU1ERTFYRngwWlhOMGJXRndYRnhwYm1SbGVDNXFjeUpkTENKdVlXMWxjeUk2VzEwc0ltMWhjSEJwYm1keklqb2lJaXdpYzI5MWNtTmxjME52Ym5SbGJuUWlPbHNpSWwxOSJdfQ=="
]
}

Exclude .js extension

We always use the .jsx extension for files with JSX syntax and don't want to run regular .js files through reactify. It would be nice to have the possibility to configure reactify to skip .js files.

This seems to be impossible currently as the js extension is included to no matter what the options.extension specifies here:

var extensions = ['js', 'jsx']

Push last update to npm (plz)

Sorry for this issue, I know I'm looking a bit harsh on this one, since you've just updated the code to match the latest react-tools 1 hour ago (0.9.0-rc1). Do you know when you're gonna push it ? Thanks in advance, and sorry again for this useless issue.

support for flow types

When I run browserify -t reactify main.js with these files:

add.js

/* @flow */
module.exports = function (x: number, y: number) : number {
  return x + y;
};

main.js

/* @flow */
var add = require('./add');
console.log(add(3, 1));

I get this error:

module.exports = function (x: number, y: number) : number {
                            ^
ParseError: Unexpected token

The JSX transform that comes with react tools v. 0.12.2 can strip out flow type annotations from this file with jsx --strip-types (not sure if later versions do this). I'm new to NPM and node, etc. so I'm not sure how to add this transform to reactify. I tried changing the react-tools field in my project's node_modules/reactify/package.json to "~0.12.2" and then ran npm build, but it didn't seem to have any effect.

Is there a way to strip out flow types with reactify? Or do I need to run jsx in a separate command before running browserify?

wrong version of react-tools dependency

here is the version decleared in package.json:

"react-tools": ">= 0.11.0"

a few minutes ago i run npm install and got an invalide version of react-tools in reactify:

├─┬ [email protected]
│ ├─┬ [email protected] invalid

this cause all jsx tags compile to React.createElement, not the old one React.DOM.tagName.
i think the version should write like this:

"react-tools": "~0.11.0"

semver in npm

react 0.12 changed a lot... haven't look into it yet.

Configuring ES6 in task?

I have a browserify task that is configured like so:

module.exports = function(grunt) {

  grunt.config.set('browserify', {
    dev: {
      src: 'assets/js/main.jsx',
      dest: '.tmp/public/js/main.js',
      options: {
        debug: true,
        extensions: ['.jsx'],
        transform: ['reactify']
      }
    }
  });

  grunt.loadNpmTasks('grunt-browserify');
};

I tried configuring it to use es6 this way:

module.exports = function(grunt) {

  grunt.config.set('browserify', {
    dev: {
      src: 'assets/js/main.jsx',
      dest: '.tmp/public/js/main.js',
      options: {
        debug: true,
        extensions: ['.jsx'],
        transform: ['reactify', {'es6': true}]
      }
    }
  });

  grunt.loadNpmTasks('grunt-browserify');
};

This causes an error though:

Error: path must be a string

I can't understand from the docs how to do this given that I don't want to configure the transform in my package.json. Any help would be appreciated.

v2

Following the https://ghub.io/esmify and related transforms,
that would be nice to make a cumulative transform, making browserify work for react-apps and even better.

So far the subset of create-react-app it is done in https://github.com/dy/budo, but that would be nice to have it extended to cover more use-cases, first of all, importing css, raw data and handling JSX in babel-less way.

@andreypopp do you have an opinion on that?

lower case custom HTML elements not working

require('react').React.render(
  <logo />,
  document.getElementById("whatever")
);

Reactify gives Lower case component names (logo) are no longer supported in JSX: See http://fb.me/react-jsx-lower-case
It's not a React component, it's my custom HTML element which the linked Gist says are supported now, as does the the release notes for React 0.12.

Using
Reactify 1.0.0
React 0.12.2

typescript extensions

I'm not sure if this is something that is entirely possible right now. But it would be sweet if reactify could support tsify via extensions a la coffeeify.

Edited to add: something like this works perfectly fine today:

watchify -p [tsify] -t [ reactify --extension "everything" ] lib/js/app.ts -o bundle.js

The problem comes in when jsx syntax is introduced into a ts file.

Watchify fails with reactify

I'm using browserify, watchify and reactify in a project, browserify runs perfect, but watchify is failing, I think could be a problem of reactify or watchify, I'm reporting the issue here and watchify github, the watcher is initiated by npm start in package.json as follows:

{...
  "scripts": {
    "start": "watchify -o js/bundle.js -v -d js/app.js",
    "build": "browserify . -t [envify --NODE_ENV production] | uglifyjs -cm > js/bundle.min.js",
    "test": "jest"
  },
  "browserify": {
    "transform": [
      "reactify",
      "envify"
    ],
...}

Terminal output:

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: watch ENOSPC
    at errnoException (fs.js:1019:11)
    at FSWatcher.start (fs.js:1051:11)
    at Object.fs.watch (fs.js:1076:11)
    at createFsWatchInstance (/miranda_frontend/node_modules/watchify/node_modules/chokidar/lib/nodefs-handler.js:37:15)
    at setFsWatchListener (/miranda_frontend/node_modules/watchify/node_modules/chokidar/lib/nodefs-handler.js:80:19)
    at EventEmitter.NodeFsHandler._watchWithNodeFs (/miranda_frontend/node_modules/watchify/node_modules/chokidar/lib/nodefs-handler.js:228:14)
    at EventEmitter.NodeFsHandler._handleFile (/miranda_frontend/node_modules/watchify/node_modules/chokidar/lib/nodefs-handler.js:255:21)
    at EventEmitter.<anonymous> (/miranda_frontend/node_modules/watchify/node_modules/chokidar/lib/nodefs-handler.js:468:21)
    at Object.oncomplete (fs.js:107:15)

Error: Arguments to path.resolve must be strings

Using gulp, I am trying to reactify my javascript files. But I get Arguments to path.resolve must be strings exception.

var gulp = require('gulp');
var reactify = require('reactify');

gulp.task('js', function () {
  return gulp.src('/public/javascripts/src/*.jsx')
    .pipe(reactify())
    .pipe(gulp.dest('/public/javascripts/dist'))
});

When I comment out .pipe(reactify()), I don't get that error. Any suggestions?

Full error:

[11:08:34] Using gulpfile ~/Development/Github/express-react-todo/gulpfile.js
[11:08:34] Starting 'js'...
path.js:422
      throw new TypeError('Arguments to path.resolve must be strings');
      ^
TypeError: Arguments to path.resolve must be strings
    at Object.posix.resolve (path.js:422:13)
    at DestroyableTransform.saveFile [as _transform] (/Users/mikecho/Development/Github/express-react-todo/node_modules/gulp/node_modules/vinyl-fs/lib/dest/index.js:36:26)
    at DestroyableTransform.Transform._read (/Users/mikecho/Development/Github/express-react-todo/node_modules/gulp/node_modules/vinyl-fs/node_modules/through2/node_modules/readable-stream/lib/_stream_transform.js:184:10)
    at DestroyableTransform.Transform._write (/Users/mikecho/Development/Github/express-react-todo/node_modules/gulp/node_modules/vinyl-fs/node_modules/through2/node_modules/readable-stream/lib/_stream_transform.js:172:12)
    at doWrite (/Users/mikecho/Development/Github/express-react-todo/node_modules/gulp/node_modules/vinyl-fs/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:237:10)
    at writeOrBuffer (/Users/mikecho/Development/Github/express-react-todo/node_modules/gulp/node_modules/vinyl-fs/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:227:5)
    at DestroyableTransform.Writable.write (/Users/mikecho/Development/Github/express-react-todo/node_modules/gulp/node_modules/vinyl-fs/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:194:11)
    at Stream.ondata (stream.js:51:26)
    at Stream.emit (events.js:107:17)
    at drain (/Users/mikecho/Development/Github/express-react-todo/node_modules/reactify/node_modules/through/index.js:36:16)

Update to Browserify v3

Hello,

I'd love to see this plugin updated to support Browserify v3, so that config is simple and declarative in the package.json. What's your plan about it ?

Fix version dependencies

You can't have "stable" versions and include this dependency.

"react-tools": ">= 0.11.0"

This will install 0.12 when people are really wanting 0.11. You should make this ~0.11.0 or ^0.11.0.

This is affecting a number of people who haven't upgraded their react but simply reinstalled their npm dependencies. (eg, people still using reactify 0.13.x).

This hasn't really been a problem in the past because the JSX transform hasn't really changed. But now that it has this is causing problems.

Use together with es6ify

I'm combining this with es6ify (I didn't realize it could do ES6 transforms, too, though it seems like it would also be more limited in terms of what is supports).

es6ify and reactify have been working great together, except if I enable "traceurOverrides: asyncFunctions" because I want to use the "await" keyword. I have to run reactify first, and await doesn't get through: Parse Error: Line 18: Unexpected identifier while parsing file.

Is there something that can be done about this?

JSX in modules isn't transformed

I'm not sure if this is something that can be resolved, but wanted to report it in case. Might be a browserify issue, or configuration option I've missed ...?

I'm developing a generic UI control in React, and just moved it out of my project and into its own package - which I've published to npm, and am continuing to develop using npm link.

Unfortunately, as soon as my code is inside the node_modules folder, it stops being transformed, and I start getting errors. (It still has the /** @jsx React.DOM */ pragma at the start of the file)

It seems I can work around this by either

  • Transforming the JSX in my package independently
  • Not using JSX in my packages

Both are doable but it would be nice if I could just use my existing workflow to transform everything I'm including, regardless of whether it's in my project or a package.

Can't render string without parent.

I'm trying to make a component void of html. You can see an example of this here. I'm using the displayName property which JSX sets. However I get an error with code like this:

var LiquidAssign = module.LiquidAssign = React.createClass({
  displayName: "LiquidAssign",
  render: function() {
    return (
      {"{% assign "+this.props.name+" = "+this.props.value+"%}"}
    )
  }
});

And not with this:

var LiquidAssign = module.LiquidAssign = React.createClass({
  displayName: "LiquidAssign",
  render: function() {
    return (
     <div>
      {"{% assign "+this.props.name+" = "+this.props.value+"%}"}
     </div>
    )
  }
});

I'm getting

Parse Error: Line 18: Unexpected token +

jsx modules not found

Hello

I use browserify and reactify. All the react components have a .jsx extension
but when I try to create the bundle using
$ browserify -x jsx -t [ reactify -x jsx ] app.jsx > bundle.js
I have the folowwing error Error: module "compo" not found

Here is a simplified example.
app.jsx

/**
 * @jsx React.DOM
 */
var compo = require('./compo.jsx');

and
compo.jsx

/**
 * @jsx React.DOM
 */
var Compo = React.createClass({
  render: function() {
    return (
      <h1>HelloWorld</h1>
    );
  }
});

module.export = compo

I need to do require('./compo.jsx') or to replace file extension from jsx to js in order to remove the error. Do I miss something using --extension ? Is that something normal ?
Thanks.

Lionel

Unexpected token < while parsing file

I can't get reactify to work. No matter what I do I keep getting this Parse Error.

ReactifyError: /path/to/my/file: Parse Error: Line 6: Unexpected token < while parsing file: /path/to/my/file

My file itself contains basically nothing for testing purposes.

var React = require('react');

var App = React.createClass({
  render: function() {
    return {
      <div>
        <p>testing</p>
      </div>
    };
  }
});

What am I doing wrong?

Watchify no longer works if there is a JSX syntax error.

When I have watchify running and I purposefully create an error in the JSX file (create a <div> but don't close it), watchify begins to process the change and then just seems to hang. If I fix the error, watchify never seems to begin working again. Is there some sort of error handling I need to add to allow watchify to recover from the bad JSX file?

I've included my browserify task below for reference. I've removed the live server reload and have simplified the task as much as I could, and the problem still persisted.

        var bundleMethod = options.isWatching ? watchify : browserify,
            bundler = bundleMethod('../../../app/' + application.directory + '/src/script/main-' + application.id + '.js',
                {
                    basedir: __dirname,
                    extensions: ['.jsx', '.scss']
                });

        bundler.transform(reactify);

        options.externals.forEach(function (external) {
            bundler.exclude(external);
        });

        rebundle = function () {
            return bundler.bundle({ debug: env.isDevelopmentBuild() })
                .pipe(source('app-' + application.id + '.js'))
                .pipe(gulp.dest(options.target + '/' + application.directory + '/script'));
        };

        var rebundleAndReload = function () {
            return rebundle().pipe(server.reload());
        };

        bundler.on('update', rebundleAndReload);

        return rebundle();

Issue with running `--es6` with watchify

Running watchify -t reactify main.js -o bundled.js would run as expected & keep rebundling whenever file changes. watchify -t reactify --es6 main.js -o bundled.js, on the other hand, runs for single time and then stops.
Do you have some clues on what might be different in this case and what can I do to troubleshoot the issue?

Error: Cannot find module while using params

Hi,

When I use reactify without any options, like browserify -t reactify in.js -o out.js everything is fine. However, when I try to add additional flags browserify -t [ reactify --es6 ] in.js -o out.js I'm getting an error:

Error: Cannot find module 'PROJ_DIR/reactify' from 'PROJ_DIR'

I'm using zsh instead of bash. Did anyone encounter such an issue?

Thanks,
Adam

Unexpected token on symlinks

I have my src directory symlink to node_modules

$ cd node_modules; ln -s ../src app

when i dont know if i require a component like this

var Input = require('app/component/input');

I get the Parsin file /home/rkmax/project/node_modules/app/component/input.js Unexpected token`

if i use the relative path works fine :(

Avoid exiting process on error?

I'm not too familiar with the internals here, but we use it with gulp-watch and sometimes what we save doesn't work yet, and so reactify crashes my watching gulp process and I have to restart it.

If it could just print the error, the lines that it is on, and then bail, that would be appreciated.

Reactify not transforming JSX file

OK so this is super weird, I'm usually a happy user of reactify, but in one case of mine, I can't get it to perform the transform! I have this:

 b2 = browserify();
 b2.transform(reactify);
 b2.require(path.resolve(__dirname, 'client.jsx'), {basedir: '.', expose: '__isoclient'});
 b2.bundle(...);

At the top of client.jsx, I have specified:

/**
* @jsx React.DOM
*/

This throws an Unexpected token error on the first < of a jsx tag.

Weirdly, browserify -t reactify client.jsx works fine.

What could be going on here?

Watchify transform failing with reactify on error

browserify/watchify#64

I'm running into this issue from Watchify which was closed because their tests passed, even though the error still seems to be there. I'm wondering if it's something in the implementation with Reactify.

Terminal output:

[14:09:51] Using gulpfile /MyWebsite/gulpfile.js
[14:09:51] Starting 'watch'...
[14:09:51] Bundle rebuilt
[14:09:51] Finished 'watch' after 15 ms
[14:09:51] Starting 'default'...
[14:09:51] Finished 'default' after 4.53 μs

events.js:72
        throw er; // Unhandled 'error' event
              ^
ReactifyError: /MyWebsite/js/components/SearchDeals.jsx: Parse Error: Line 22: Expected corresponding XJS closing tag for h2 while parsing file: /MyWebsite/js/components/SearchDeals.jsx
    at throwError (/MyWebsite/node_modules/reactify/node_modules/jstransform/node_modules/esprima-fb/esprima.js:2343:21)
    at parseXJSElement (/MyWebsite/node_modules/reactify/node_modules/jstransform/node_modules/esprima-fb/esprima.js:5998:17)
    at parseXJSChild (/MyWebsite/node_modules/reactify/node_modules/jstransform/node_modules/esprima-fb/esprima.js:5920:21)
    at parseXJSElement (/MyWebsite/node_modules/reactify/node_modules/jstransform/node_modules/esprima-fb/esprima.js:5992:31)
    at parseXJSChild (/MyWebsite/node_modules/reactify/node_modules/jstransform/node_modules/esprima-fb/esprima.js:5920:21)
    at parseXJSElement (/MyWebsite/node_modules/reactify/node_modules/jstransform/node_modules/esprima-fb/esprima.js:5992:31)
    at parsePrimaryExpression (/MyWebsite/node_modules/reactify/node_modules/jstransform/node_modules/esprima-fb/esprima.js:2906:20)
    at parseLeftHandSideExpressionAllowCall (/MyWebsite/node_modules/reactify/node_modules/jstransform/node_modules/esprima-fb/esprima.js:2990:61)
    at parsePostfixExpression (/MyWebsite/node_modules/reactify/node_modules/jstransform/node_modules/esprima-fb/esprima.js:3030:20)
    at parseUnaryExpression (/MyWebsite/node_modules/reactify/node_modules/jstransform/node_modules/esprima-fb/esprima.js:3097:16)

package.json versions I'm running

{
  "name": "mywebsite",
  "version": "0.0.1",
  "devDependencies": {
    "browserify": "^5.10.0",
    "gulp": "^3.8.7",
    "gulp-jshint": "^1.8.4",
    "gulp-react": "^1.0.0",
    "gulp-rename": "^1.2.0",
    "gulp-sass": "^0.7.3",
    "gulp-sourcemaps": "^1.1.1",
    "gulp-uglify": "^0.3.1",
    "gulp-util": "^3.0.0",
    "jshint-stylish": "^0.4.0",
    "minifyify": "^4.0.4",
    "reactify": "^0.14.0",
    "vinyl-source-stream": "^0.1.1",
    "watchify": "^1.0.5"
  },
  "dependencies": {
    "underscore": "^1.7.0"
  }

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.