简体   繁体   中英

Webpack, React, JSX, Babel - Unexpected token <

This is what I have, using ExpressJS:

|-- app
|   |-- index.js
|-- node_modules
|   |-- babel-core
|   |-- babel-loader
|   |-- babel-preset-react
|   |-- express
|   |-- react
|   |-- react-dom
|   |-- webpack
|-- public
|   |-- js
|   |   |-- app.js
|   |-- index.html
|-- .babelrc
|-- index.js
|-- package.json
|-- webpack.config.js

/webpack.config.js

module.exports = {
    entry: [
        './app/index.js'
    ],
    module: {
        loaders: [{
            test: /\.js$/,
            include: __dirname + '/app',
            loader: "babel-loader",
            query: {
                presets:['react']
            }
        }]
    },
    output: {
        filename: "app.js",
        path: __dirname + '/public/js'
    }
};

/app/index.js

var React = require("react");
var ReactDOM = require("react-dom");
var People = React.createClass({
    ...
});
ReactDOM.render(<People />, document.getElementById('app'));

/.babelrc

{
  "presets": [
    "react"
  ]
}

When I run webpack I get:

Module parse failed: /app/index.js Unexpected token < You may need an appropriate loader to handle this file type.

When I replace <People /> with React.createElement(People, {}) it works just fine.

I have the babel-preset-react module. I have presets:['react'] with the babel-loader loader. I have the .babelrc file.

Why can webpack/babel not parse the <People /> JSX..?

This turned out to be an issue with my include path. I had:

include: __dirname + '/app'

I'm now using path :

include: path.join(__dirname, '/app')

Which works! I'm on Windows, don't know if that makes a difference. Think I'll start using path routinely from now on.

Would've been nice for the webpack error to be something like Can't find include folder/files .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM