[英]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. 我正在尝试创建一个工作流,我可以使用TypeScript编写React模块,并通过Gulp.js自动编译为JavaScript。 I am using TypeScript 1.6.2, gulp-react and gulp-typescript.
我正在使用TypeScript 1.6.2,gulp-react和gulp-typescript。
My .tsx
file looks like this now: 我的
.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'));
My problem is this line: import React = __React;
我的问题是这一行:
import React = __React;
When I leave it out, I get the error 当我把它遗漏时,我得到了错误
error TS2304: Cannot find name 'React'.`
错误TS2304:找不到名称'React'
when compiling .tsx
to .js
(but it still compiles to JSX, and I can use the output). 在将
.tsx
编译为.js
(但它仍然编译为JSX,我可以使用输出)。 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. 当我把它放入时,我可以编译而没有错误,但当我尝试在浏览器中使用该文件时,我得到一个
Uncaught ReferenceError: __React is not defined
当然Uncaught ReferenceError: __React is not defined
。
This is how my gulptask looks like: 这就是我的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'));
});
Is there a workaround for this? 这有解决方法吗? Or am I missing something here?
或者我在这里遗漏了什么?
Okay, I found a solution. 好的,我找到了解决方案。 First install the React global definition via tsd :
首先通过tsd安装React全局定义:
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): 这将在您的
typings
目录中创建一个文件react-global.d.ts
,您必须在根组件文件中引用该文件(该路径是相对的,因此请根据您的需要进行调整):
/// <reference path="../../../../typings/react/react-global.d.ts" />
After that it compiles without errors. 之后,它编译没有错误。
where I can write react modules using typescript and automatic compiling to js via gulp
在哪里我可以使用打字稿编写反应模块,并通过gulp自动编译为js
Highly recommend you don't use global modules. 强烈建议您不要使用全局模块。 Instead compile with
--module commonjs
and embrace the react / webpack / nodejs ecosystem. 而是使用
--module commonjs
编译并包含react / webpack / nodejs生态系统。
You can checkout an example application here : https://github.com/basarat/tsb/tree/master 您可以在此处查看示例应用程序: https : //github.com/basarat/tsb/tree/master
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.