我创建了一个 jsx 文件,如下所示
/** @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
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'));
});
})();
问题是当我在浏览器中运行 js 文件时出现 Uncaught ReferenceError: dom is not defined 。改造后添加dom。知道如何解决这个问题吗?
最佳答案
在使用基本的 React 应用程序时遇到同样的问题。
原来罪魁祸首在我的 webpack.config.js 中。我有:
plugins: [
["transform-react-jsx", {
"pragma": "dom"
}]
]
babel 的默认 pragma 是 React.createElement ( https://babeljs.io/docs/plugins/transform-react-jsx/ )。
事实是我没有理由选择这个选项,我只是复制/粘贴 来自上面的链接。
从文档中,我应该导入我拥有的“dom”模块 指定并确保我安装了 babel-plugin-jsx-pragmatic。
这个插件的文档在这里https://www.npmjs.com/package/babel-plugin-jsx-pragmatic并解释一下 pragma。
我通过简单地删除 'pragma' 选项解决了这个问题,这样我就可以 只需使用默认的(附上我的 webpack.config.js 的一部分以提供更多上下文): -- 我正在使用 webpack 2.6.1
...
module: {
rules: [{
//a regexp that tells webpack to use the following loaders on all
//.js and .jsx files
test: /\.js$/,
loader: 'babel-loader',
options: {
babelrc: false,
presets: ["es2016", "react", "stage-0"],
plugins: [
["transform-react-jsx"]
]
},
//we definitely don't want babel to transpile all the files in
//node_modules. That would take a long time.
exclude: /node_modules/
},
...
关于javascript - jsx转js后dom is not defined报错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35281619/