TypeScript, React and Gulp.js - defining react

TypeScript, React and Gulp.js - defining react

本文关键字:defining react js Gulp React and TypeScript      更新时间:2023-09-26

我正在尝试制作一个工作流,在那里我可以使用TypeScript编写React模块,并通过Gulp.js自动编译为JavaScript。我使用的是TypeScript 1.6.2, gulp-react和gulp-typescript。

我的.tsx文件现在是这样的:

/// <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'));

我的问题是这一行:import React = __React;

当我忽略它时,我得到错误

错误TS2304: Cannot find name 'React'. '

.tsx编译为.js(但它仍然编译为JSX,我可以使用输出)。当我把它放进去时,我可以编译没有错误,但是当我试图在浏览器中使用该文件时,我得到一个Uncaught ReferenceError: __React is not defined,当然。

这是我的gulptask的样子:

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'));
});

是否有解决这个问题的方法?还是我遗漏了什么?

好吧,我找到了一个解决方案。首先通过tsd:

安装React全局定义
tsd install react-global

这将在您的typings目录中创建一个文件react-global.d.ts,您必须在根组件文件中引用该文件(路径是相对的,因此根据您的需要调整它):

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

在这里我可以使用typescript编写react模块,并通过gulp自动编译成js

强烈建议不要使用全局模块。相反,用--module commonjs编译,拥抱react/webpack/nodejs生态系统。

您可以在这里查看示例应用程序:https://github.com/basarat/tsb/tree/master