Webpack build Failed, Throws Unexpected Token Error JSX syntax

房东的猫 提交于 2021-01-28 01:28:36

问题


ERROR in ./client/index.js Module build failed: SyntaxError: Unexpected token (31:4)

const Root = () => { return (

<ApolloProvider client={client}>
 ^
   <Router history={hashHistory}>

My Webpack config file below:

const path = require('path'),
webpack = require("webpack"),
clientPath = path.join(__dirname, 'client'),
HtmlWebpackPlugin = require('html-webpack-plugin');



module.exports = {
entry: path.join(clientPath, 'index.js'),
output: {
path: __dirname,
filename: 'bundle.js'
},
module: {
 rules: [
  {
    use: 'babel-loader',
    test: /\.js$/,
    exclude: /node_modules/
  },
  {
    use: ['style-loader', 'css-loader'],
    test: /\.css$/
  },
  {
    test: /\.(jpe?g|png|gif|svg)$/i,
    loaders: [
        'file-loader?hash=sha512&digest=hex&name=[hash].[ext]',
        'image-webpack-loader?bypassOnDebug&optimizationLevel=7&interlaced=false'
    ]
  },
  {
      test: /\.(eot|svg|ttf|woff|woff2)$/,
      loader: 'file-loader'
  }
],
loaders: [
  { test: /\.jsx$/, exclude: /node_modules/, loader: "babel-loader" }
]
},
plugins: [
new HtmlWebpackPlugin({
  template: 'client/index.html'
})

] };

I am not able to build , it throws Unexpected token error while I have no syntactical mistake in code, Its just not able to recognise react code style

I have tried changing js to jsx inside webpack config at this place

{
use: 'babel-loader',
test: /\.jsx$/,
exclude: /node_modules/
}

Then it throws different error like

Module parse failed: /client/index.js Unexpected token (31:4)
You may need an appropriate loader to handle this file type.

回答1:


It was my mistake only, ".babelrc" file was missing in my directory so I have created a file inside my app directory at root level and put this content into that file

.babelrc

{
 "presets": ["env", "react"]
}

And tried with npm run-script build....succeeded!!!!




回答2:


I see two possible causes:

1) loaders: [ { test: /\.jsx$/, exclude: /node_modules/, loader: "babel-loader" } ] will do nothing as loaders should be specified in module.rules so nothing is handling jsx files. This can be done to handle both js and jsx files using regex /\.jsx?/

2) The babel loader has no presets so unless they are specified in a .babelrc ypou arent showing, then you need to add the necessary presets to the loader

These should both be remedied by...

npm install babel-preset-react babel-preset-es2015

module: {
 rules: [
  {
    test: /\.jsx?$/,
    exclude: /node_modules/,
    use: { 
      loader: 'babel-loader',
      options: {
        presets: ['es2015', 'react']
      }
    }
  },
  //...
}


来源:https://stackoverflow.com/questions/48075620/webpack-build-failed-throws-unexpected-token-error-jsx-syntax

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