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

匿名 (未验证) 提交于 2019-12-03 01:36:02

问题:

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:

回答1:

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')],  


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!