小编典典

babel-loader jsx SyntaxError:意外令牌

reactjs

我是React + Webpack的初学者。

我在Hello World Web应用程序中发现一个奇怪的错误。

我在webpack中使用babel-loader来帮助我将jsx转换为js,但是babel似乎无法理解jsx语法。

这是我的依赖项:

"devDependencies": {
  "babel-core": "^6.0.14",
  "babel-loader": "^6.0.0",
  "webpack": "^1.12.2",
  "webpack-dev-server": "^1.12.1"
},
"dependencies": {
  "react": "^0.14.1"
}

这是我的 webpack.config.js

var path = require('path');
module.exports = {
  entry: ['webpack/hot/dev-server',path.resolve(__dirname, 'app/main.js')],
  output: {
    path: path.resolve(__dirname, 'build'),
    filename: 'bundle.js'
  },
  module: {
      loaders: [
          { test: /\.js$/, exclude: /node_modules/, loader: "babel-loader"}
      ]
  }
};

这是我的 app/main.js

var React = require("react");
React.render(<h1>hello world</h1>,document.getElementById("app"));

这是错误消息

ERROR in ./app/main.js
Module build failed: SyntaxError: ~/**/app/main.js: Unexpected token (2:13)
  1 | var React = require("react");
> 2 | React.render(<h1>hello world</h1>,document.getElementById("app"));
    |              ^
at Parser.pp.raise (~/**/node_modules/babylon/lib/parser/location.js:24:13)

谢谢你们


阅读 317

收藏
2020-07-22

共1个答案

小编典典

添加“ babel-preset-react”

npm install babel-preset-react

并在webpack.config.js中向babel-loader添加“预设”选项

(或者您可以将其添加到您的.babelrc或package.js:http
://babeljs.io/docs/usage/babelrc/ )

这是一个webpack.config.js示例:

{ 
    test: /\.jsx?$/,         // Match both .js and .jsx files
    exclude: /node_modules/, 
    loader: "babel", 
    query:
      {
        presets:['react']
      }
}

最近发布了Babel 6,并进行了重大更改:https :
//babeljs.io/blog/2015/10/29/6.0.0

如果您使用的是react 0.14,则应使用ReactDOM.render()(from require('react- dom'))而不是React.render()https
:
//facebook.github.io/react/blog/#changelog

更新2018

不推荐使用Rule.query,而使用Rule.options。webpack 4中的用法如下:

npm install babel-loader babel-preset-react

然后在您的webpack配置中(作为module.exports对象中module.rules数组中的条目)

{
    test: /\.jsx?$/,
    exclude: /node_modules/,
    use: [
      {
        loader: 'babel-loader',
        options: {
          presets: ['react']
        }
      }
    ],
  }
2020-07-22