[英]Using reactjs with requirejs
最近,我开始使用reactjs
和backbonejs
路由器来构建应用程序。
我通常使用requirejs
进行依赖和代码管理。 但是,当我尝试包含包含jsx
语法的文件时出现问题。
这就是我的router.js
:
define(["backbone", "react"], function(Backbone, React) {
var IndexComponent = React.createClass({
render : function() {
return (
<div>
Some Stuff goes here
</div>
);
}
});
return Backbone.Router.extend({
routes : {
"": "index"
},
index : function() {
React.renderComponent(<IndexComponent />, document.getElementById('index'));
}
});
});
如何将IndexComponent放在自己的文件中并在此文件中调用它? 我已经尝试了通常的方法(与我使用骨干和反应相同)但由于jsx
语法而jsx
。
所以我自己弄清楚了。
我从这个repo获得了必要的文件和指令: jsx-requirejs-plugin 。
有一次,我JSX插件和修改的版本JSXTransformer ,我改变了我的代码存储库中的指示:
require.config({
// ...
paths: {
"react": "path/to/react",
"JSXTransformer": "path/to/JSXTransformer",
"jsx": "path/to/jsx plugin"
...
}
// ...
});
然后,我可以通过jsx!
引用JSX文件jsx!
插件语法。 例如,要加载组件目录中的Timer.jsx文件:
require(['react', 'jsx!components/Timer'], function (React, Timer) {
...
React.renderComponent(<Timer />, document.getElementById('timer'));
...
});
我也可以使用相同的代码访问其中jsx
语法的.js
文件:
require(['react', 'jsx!components/Timer'], function (React, Timer) {
...
React.renderComponent(<Timer />, document.getElementById('timer'));
...
});
另外,我不需要使用jsx
语法将/** @jsx React.DOM */
放在文件的顶部。
希望能帮助到你。
反对工具(包括JSX)已被弃用,有利于Babel( https://facebook.github.io/react/blog/2015/06/12/deprecating-jstransform-and-react-tools.html )。 没有“转换”步骤,我找不到这样做的方法,所以这是我的咕噜声解决方案。
您可以安装grunt-babel(npm install grunt-babel)并配置如下任务:
babel: {
options: {
sourceMap: false,
modules: "common"
},
dist: {
files: [{
expand: true,
src: ['js/components/*.jsx'],
dest: 'dist',
ext:'.js'
}]
}
}
只需将其添加到您的grunt任务列表中:
grunt.registerTask('default', ['clean', 'copy', 'babel', 'http-server']);
Babel会将您的JSX转换为可以指定为RequireJS依赖项的JS文件,而无需其他配置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.