我正在关注RGR上相对较旧的教程(自2014年起)。我不得不使用React,Webpack和Babel的更新版本,因此存在一些差异。到目前为止,一切都在工作,除非我尝试将JSX编译到webpack中,它给了我一个构建错误。
ERROR in ./public/js/app.js
Module build failed: SyntaxError: Unexpected token (7:15)
5 | class Hello extends React.Component {
6 | render() {
7 | return <h3>Hello Webpack!</h3>;
| ^
8 | }
9 | }
10 |
以下是我的React文件:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
class Hello extends React.Component {
render() {
return <h3>Hello Webpack!</h3>;
}
}
ReactDOM.render(<Hello />, document.getElementById('react'));
这是我的webpack.config.js文件
module.exports = {
entry: "./public/js/app.js",
output: {
path: __dirname + "/public",
filename: "bundle.js"
},
module: {
loaders: [
{test: /\.js$/,
loader: 'babel-loader' }
]
}
}
另外,这是我的package.json文件
{
"name": "rgrjs",
"version": "1.0.0",
"description": "a collection of educational resources about React, GraphQL, and Relay",
"main": "index.js",
"scripts": {
"start": "node server.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/krisxcrash/rgr-stack.git"
},
"author": "kristine martin",
"license": "ISC",
"bugs": {
"url": "https://github.com/krisxcrash/rgr-stack/issues"
},
"homepage": "https://github.com/krisxcrash/rgr-stack#readme",
"dependencies": {
"babel-loader": "^7.1.2",
"create-react-class": "^15.6.2",
"express": "^4.16.2",
"react": "^16.2.0",
"react-dom": "^16.2.0"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-preset-env": "^1.6.1"
}
}
任何人都可以告诉我为什么在返回后没有读取<h3>
并在webpack尝试捆绑时导致错误?
答案 0 :(得分:0)
您错过了一些预设:
首先执行npm install:
npm install babel-core babel-preset-es2015 babel-preset-react --save-dev
还在根项目目录中创建一个.babelrc,并包括:
{
"presets": ["es2015","react"]
}
同样在webpack配置的加载器部分中,将此包含在jsx:
中{ test: /\.jsx?$/, exclude: /node_modules/, use: ['babel-loader'] }