React,babel,webpack不parsingjsx代码
webpack.config.js
module.exports = { context: __dirname + "/app", entry: { javascript: "./app.js", html: "./index.html", }, resolve: { extensions: ['', '.js', '.jsx'] }, output: { filename: "app.js", path: __dirname + "/dist", }, module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: "babel-loader", }, { test: /\.html$/, loader: "file?name=[name].[ext]", }, ], }, }
的package.json
{ "name": "react-webpack-project", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "devDependencies": { "babel": "^6.0.15", "babel-core": "^6.0.20", "babel-loader": "^6.0.1", "file-loader": "^0.8.4", "webpack": "^1.12.2" }, "dependencies": { "react": "^0.14.2" } }
应用程序/ app.js
import React from "react"; import Greeting from "./greeting"; React.render( <Greeting name="World"/>, document.body );
经过四处搜寻,我看到了完全相同的问题,但没有一个答案似乎适用于我。 运行webpack
时出现以下错误:
错误在./app.js中
模块构build失败:SyntaxError:path / to / project / react-webpack-project / app / app.js:意外的标记(5:2)
React.render( <Greeting name="World"/>, document.body );
我不知道为什么我仍然得到这个错误。 我猜测它与我的webpack.config.js文件有关,但不是100%是什么问题。
首先:如果你正在使用React v ^ 0.14,你应该使用React-Dom来渲染你的代码。 https://www.npmjs.com/package/react-dom
其次,这应该解决您的问题: babel-loader jsx SyntaxError:意外的标记
您需要将预设添加到您的babel-loader:
{ test: /\.jsx?$/, exclude: /node_modules/, loader: "babel-loader", presets: ['es2015', 'react'] },
我目前正在使用React 0.14.3。 ReactDOM解决scheme不起作用,也没有将babel预设添加到webpack.config.js中。 基本上,这些解决scheme似乎只有在您定义了一个加载器的情况下才能正常工作,但我同时拥有babel-loader和react-hot加载器。
DID的工作是安装babel react预设模块:
npm install babel-preset-react
然后使用以下命令在我的项目目录中创build一个.babelrc文件:
{ "presets": ['react'] }
这被logging在http://babeljs.io/docs/plugins/preset-react/ ,正如Abhinav Singi
对我来说,答案是在查询块中包含预设:
query: { presets: ['react', 'es2015'] }
这是帮助我解决这个问题。
在同一目录webpack.config.js上创build新的.babelrc
文件。 将此添加到.babelrc
{ "stage": 2, "env": { "development": { "plugins": [ "react-display-name", "react-transform" ], "extra": { "react-transform": { "transforms": [{ "transform": "react-transform-hmr", "imports": ["react"], "locals": ["module"] }] } } } } }