我是React + Webpack的初学者。

我在我的hello world网页应用程序里发现了一个奇怪的错误。

我在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)

谢谢你们。


当前回答

下面的方法帮助了我(包括react-hot, babel loader和es2015, react presets):

loaders: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loaders: ['react-hot', 'babel?presets[]=es2015&presets[]=react']
      }
]

其他回答

这对我来说非常合适

{
    test: /\.(js|jsx)$/,
    loader: 'babel-loader',
    exclude: /node_modules/,
    query: {
        presets: ['es2015','react']
    }
},

对我来说,解决方案是用以下内容创建文件.babelrc:

{
  "presets": ["react", "es2015", "stage-1"]
}

下面的方法帮助了我(包括react-hot, babel loader和es2015, react presets):

loaders: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loaders: ['react-hot', 'babel?presets[]=es2015&presets[]=react']
      }
]

我在从巴别塔5迁移到巴别塔6时遇到了类似的问题。

我只是运行babel编译src到lib文件夹babel src——out-dir lib

我将分享我的巴别塔6的设置:

确保您已经安装了以下babel 6 devDependencies

"babel-core": "^6.7.6",
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.6.0",
"babel-preset-react": "^6.5.0",
"babel-preset-stage-0": "^6.5.0"

将.babelrc文件添加到项目中:

{
  "presets": ["es2015", "stage-0", "react"]
}

你可以在这里找到HenrikJoreteg (ampersandjs)制作的一个非常好的样板:https://github.com/HenrikJoreteg/hjs-webpack

然后在webpack.config.js中

var getConfig = require('hjs-webpack')

module.exports = getConfig({
  in: 'src/index.js',
  out: 'public',
  clearBeforeBuild: true,
  https: process.argv.indexOf('--https') !== -1
})