简体   繁体   中英

React / Webpack - “Module parse failed: Unexpected token - You may need an appropriate loader to handle this file type.”

I am trying to build a simple React app using Webpack, however during run time from the Webpack dev server I get the following error:

> ERROR in ./client/components/home.js Module parse failed: Unexpected
> token (8:3) You may need an appropriate loader to handle this file
> type. |   render(){ |         return( |           <h1>Hello World!</h1> |         ) |     } 
> @ ./client/app.js 13:12-43  @ multi
> (webpack)-dev-server/client?http://localhost:8080 ./client/app.js

Here is my Webpack.config.js file contents:

var path = require('path');
var debug = process.env.NODE_ENV !== 'production';
var webpack = require('webpack');


module.exports = {
    context: __dirname,
    devtool: debug ? 'inline-sourcemap' : null,
    entry: './client/app.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'app.js'
    },
    module: {
        loaders: [{
            test: /\.js?$/,
            exclude: /(node_modules|bower_components)/,
            include: [path.resolve(__dirname, 'client/app.js')],
            loader: 'babel-loader',
            query: {
                presets: ['react', 'es2015', 'stage-3'],
                plugins: ['transform-react-jsx']
            }
        }, {
            test: /\.scss$/,
            include: [path.resolve(__dirname, 'sass/style.scss')],
            loaders: ['style-loader' ,'css-loader' ,'sass-loader']
        }]
    },
    plugins: debug ? [] : [
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.optimize.UglifyJsPlugin({
            mangle: false,
            sourcemap: false
        }),
    ],
};

app.js file contents import React from 'react' import ReactDOM from 'react-dom' import { Switch, BrowserRouter, Route } from 'react-router-dom' import Home from './components/home.js'

ReactDOM.render((
     <BrowserRouter>
          <Switch>
            <Route exact path="/" component={Home}/>
        </Switch>
     </BrowserRouter>
     ),
     document.getElementById('app')
)

And below is my folder structure as follows: 在此处输入图片说明

I think it might have something to do with your includes property for your loader:

// Here you are telling babel to ONLY transpile client/app.js. One file.
include: [path.resolve(__dirname, 'client/app.js')]

Should be:

// Instead, it needs to transpile ALL .js files under /client
include: [path.resolve(__dirname, 'client')], 

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