问题描述
我如下创建了一个jsx文件
I created a jsx file as below
/** @jsx dom */
(function(){
'use strict';
define([
'jquery',
'react',
'react-dom'
],
function($, React, ReactDOM){
var AppView = React.createClass({
render: function() {
return <div>Hello World</div>;
}
});
ReactDOM.render(<AppView />, document.getElementById('dsl-application'));
});
})();
并使用以下命令将jsx转换为js
And transformed the jsx to js using below command
babel --watch src --out-dir bundle --preset react
输出文件如下所示
(function () {
'use strict';
define(['jquery', 'react', 'react-dom'], function ($, React, ReactDOM) {
var AppView = React.createClass({
displayName: 'AppView',
render: function () {
return dom(
'div',
null,
'Hello World'
);
}
});
ReactDOM.render(dom(AppView, null), document.getElementById('dsl-application'));
});
})();
问题是我遇到了Uncaught ReferenceError:在浏览器中运行js文件时未定义dom的问题.转换后添加dom.有什么线索解决这个问题吗?
The problem is I got Uncaught ReferenceError: dom is not defined when I run the js file in browser. dom is added after transformation. Any clue how to fix this?
推荐答案
要将JSX转换为浏览器中的JS,您需要babel
中的browser.js
.有关简单示例,请参考 https://github.com/ruanyf/react-demos/blob/master/demo01/index.html
To transform JSX to JS in browser, you need browser.js
from babel
. For a simple example refer to https://github.com/ruanyf/react-demos/blob/master/demo01/index.html
[[基于更多信息的更新]
[[UPDATE BASED ON MORE INFO]]
使用以下文件,然后运行npm install
和webpack
,即可准备使用index.html
.
Use the following files and then run npm install
and webpack
, then your index.html
will be ready to be served.
index.html
index.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="example"></div>
<script type="text/javascript" src="bundle.js" charset="utf-8"></script>
</body>
</html>
package.json
package.json
{
"name": "another",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"react": "^0.14.7",
"react-dom": "^0.14.7"
},
"devDependencies": {
"babel-core": "^6.5.1",
"babel-loader": "^6.2.2",
"babel-preset-es2015": "^6.5.0",
"babel-preset-react": "^6.5.0",
"webpack": "^1.12.13",
"webpack-dev-server": "^1.14.1"
}
}
main.jsx
'use strict'
var React = require('react')
var ReactDOM = require('react-dom')
var AppView = require('./component.jsx')
ReactDOM.render(
<AppView />,
document.getElementById('example')
);
component.jsx
component.jsx
'use strict'
var React = require('react')
var AppView = React.createClass({
render: function(){
return(<h1>Hello, world!</h1>)
}
});
module.exports = AppView
webpack.config.js
webpack.config.js
module.exports = {
entry: './main.jsx',
output: {
path: __dirname,
filename: "bundle.js"
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel', // 'babel-loader' is also a legal name to reference
query: {
presets: ['react', 'es2015']
}
}
]
}
}
这篇关于将jsx转换为js后dom未定义错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!