【问题标题】:Webpack build Failed, Throws Unexpected Token Error JSX syntaxWebpack 构建失败,抛出意外的令牌错误 JSX 语法
【发布时间】:2018-06-13 00:34:30
【问题描述】:

./client/index.js 中的错误 模块构建失败:SyntaxError: Unexpected token (31:4)

常量根 = () => { 返回(

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

我的 Webpack 配置文件如下:

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'
})

] };

我无法构建,它会抛出 Unexpected token 错误,而我在代码中没有语法错误,它只是无法识别反应代码样式

我已经尝试在这个地方的 webpack 配置中将 js 更改为 jsx

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

然后它会抛出不同的错误,例如

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

【问题讨论】:

  • 你的 babel conf 是什么?你需要一些预设来处理 JSX

标签: javascript webpack


【解决方案1】:

这只是我的错误,我的目录中缺少“.babelrc”文件,因此我在根级别的应用程序目录中创建了一个文件并将此内容放入该文件中

.babelrc

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

并尝试使用 npm run-script build....成功!!!

【讨论】:

    【解决方案2】:

    我看到两个可能的原因:

    1) loaders: [ { test: /\.jsx$/, exclude: /node_modules/, loader: "babel-loader" } ] 不会做任何事情,因为应该在 module.rules 中指定加载程序,所以没有任何东西处理 jsx 文件。这可以使用 regex /\.jsx?/ 来处理 js 和 jsx 文件

    2) babel 加载器没有预设,因此除非它们在 .babelrc ypou 没有显示中指定,否则您需要将必要的预设添加到加载器

    这些都应该通过......来补救

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

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

    【讨论】:

      猜你喜欢
      • 2017-09-15
      • 1970-01-01
      • 2016-09-23
      • 2020-11-20
      • 2018-08-29
      • 2016-07-10
      • 2021-11-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多