![](/img/trans.png)
[英]React with Redux: Module build failed: SyntaxError: Unexpected token <
[英]'Module build failed: SyntaxError: Unexpected token' with legit React code
嘗試編譯我的React應用程序時出現錯誤。 看來Babel尚未正確配置,無法將React代碼轉換為原始JS。 我嘗試了許多不同的方法,但都沒有用。 這是我的最終代碼,我認為應該起作用:
這是我的代碼:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
sidebarOpen: false
}
this.onSetSidebarOpen = this.onSetSidebarOpen.bind(this);
}
onSetSidebarOpen: function(open) {
this.setState({sidebarOpen: open});
}
render: function() {
var sidebarContent = <b>Sidebar content</b>;
return (
<Sidebar sidebar={sidebarContent}
open={this.state.sidebarOpen}
onSetOpen={this.onSetSidebarOpen}>
<b>Main content</b>
</Sidebar>
);
}
};
這是我的.babelrc文件:
{
"presets": ["es2015", "react"],
"plugins": [
["import", { "libraryName": "antd", "style": "css" }],
"transform-class-properties",
"transform-object-rest-spread"
]
}
這是我的webpack.config.js:
const webpack = require('webpack');
module.exports = {
entry: [
'react-hot-loader/patch',
'./src/index.js'
],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader']
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{ test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader" },
{ test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader" }
]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
output: {
path: __dirname + '/public',
publicPath: '/',
filename: 'bundle.js'
},
plugins: [
new webpack.HotModuleReplacementPlugin()
],
devServer: {
contentBase: './public',
hot: true
}
};
不明白缺少了什么。 謝謝
您似乎正在添加實例字段/成員。 使用分配:
class App extends React.Component {
onSetSidebarOpen = function(open) {
this.setState({sidebarOpen: open});
};
...
}
如果以這種方式初始化,則也可以在構造函數中跳過綁定“ this”。
另一個變體:
class App extends React.Component {
onSetSidebarOpen(open) { this.setState({sidebarOpen: open}) }
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.