Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

javascript - React, babel, webpack not parsing jsx code

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/app.js

import React from "react";
import Greeting from "./greeting";

React.render(
  <Greeting name="World"/>,
  document.body
);

I have seen the exact same questions after searching around, but none of the answers seemed to apply to me. I am getting the following error when running webpack :

ERROR in ./app.js
Module build failed: SyntaxError: path/to/project/react-webpack-project/app/app.js: Unexpected token (5:2)

React.render(
  <Greeting name="World"/>,
  document.body
);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to add presets to your babel-loader:

{
        test: /.jsx?$/,
        exclude: /node_modules/,
        loader: "babel-loader",
        presets: ['es2015', 'react']  
},

http://babeljs.io/docs/plugins/#presets


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...