最近,我开始结合使用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放在自己的文件中并在此文件中调用它?我尝试了通常的方法(与我在backbone和react中使用的方法相同),但由于jsx
语法的原因而出现错误。
发布于 2014-04-30 17:42:24
所以我自己想出来了。
我从以下存储库获得了必要的文件和说明:jsx-requirejs-plugin。
一旦我有了jsx plugin和JSXTransformer的修改版本,我就按照存储库中的说明更改了代码:
require.config({
// ...
paths: {
"react": "path/to/react",
"JSXTransformer": "path/to/JSXTransformer",
"jsx": "path/to/jsx plugin"
...
}
// ...
});
然后,我可以通过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 */
放在文件的顶部。
希望能有所帮助。
发布于 2017-02-07 16:09:23
React工具(包括JSX)已经被弃用,取而代之的是Babel (https://facebook.github.io/react/blog/2015/06/12/deprecating-jstransform-and-react-tools.html)。我找不到一种没有“转译”步骤的方法,所以这是我的grunt解决方案。
您可以安装grunt-babel (npm安装grunt-babel)并配置如下任务:
babel: {
options: {
sourceMap: false,
modules: "common"
},
dist: {
files: [{
expand: true,
src: ['js/components/*.jsx'],
dest: 'dist',
ext:'.js'
}]
}
}
只需将其添加到您的任务列表中即可:
grunt.registerTask('default', ['clean', 'copy', 'babel', 'http-server']);
Babel会将你的JSX文件转换成JS文件,这些文件可以被指定为RequireJS依赖,而不需要额外的配置。
https://stackoverflow.com/questions/23381561
复制相似问题