Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript, React and Gulp.js - defining react

I am trying to make a workflow, where I can write React modules using TypeScript and automatic compiling to JavaScript via Gulp.js. I am using TypeScript 1.6.2, gulp-react and gulp-typescript.

My .tsx file looks like this now:

/// <reference path="../../../../typings/react/react.d.ts" />
import React = __React;
interface HelloWorldProps {
    name: string;
}

var HelloMessage = React.createClass<HelloWorldProps, any>({
    render: function() {
        return <div>Hello {this.props.name}</div>;
    }
});
React.render(<HelloMessage name="helloooo" />, document.getElementById('test'));

My problem is this line: import React = __React;

When I leave it out, I get the error

error TS2304: Cannot find name 'React'.`

when compiling .tsx to .js (but it still compiles to JSX, and I can use the output). When I put it in, I can compile without errors, but when I try to use the file inside the browser, I get an Uncaught ReferenceError: __React is not defined, of course.

This is how my gulptask looks like:

gulp.task('gui-tsx', function () {
    var tsResult = gulp.src(config.guiSrcPath + 'tsx/app.tsx')
        .pipe(ts({
            jsx: 'react'
        }));
    return tsResult.js.pipe(gulp.dest(config.guiSrcPath + 'jsx'));
});

Is there a workaround for this? Or am I missing something here?

like image 808
Felix Hagspiel Avatar asked Oct 04 '15 10:10

Felix Hagspiel


2 Answers

Okay, I found a solution. First install the React global definition via tsd:

tsd install react-global

This will create a file, react-global.d.ts, in your typings directory, which you have to reference in you root component file (the path is relative, so adjust it to your needs):

/// <reference path="../../../../typings/react/react-global.d.ts" />

After that it compiles without errors.

like image 85
Felix Hagspiel Avatar answered Oct 03 '22 19:10

Felix Hagspiel


where I can write react modules using typescript and automatic compiling to js via gulp

Highly recommend you don't use global modules. Instead compile with --module commonjs and embrace the react / webpack / nodejs ecosystem.

You can checkout an example application here : https://github.com/basarat/tsb/tree/master

like image 43
basarat Avatar answered Oct 03 '22 21:10

basarat