Babel/webpack 不读 jsx

Babel/webpack not reading jsx

我的 react/webpack 设置有点麻烦,它命中了 JSX 的第一位,我 "Unexpected Token" - 就像 JSX 中的第一个 < 一样。这是我的 Webpack 配置:

 const path = require('path');

 const webpack = require('webpack');

module.exports = {
entry: [
    'webpack-dev-server/client?http://localhost:8080',
    'webpack/hot/only-dev-server',
    './app/index.jsx'
],
module: {
    loaders: [{
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel-loader'
    }]
},
resolve: {
    extensions: ['', '.js', '.jsx']
},
output: {
    path: path.join(__dirname, 'dist'),
    publicPath: '/',
    filename: 'bundle.js'
},
devServer: {
    contentBase: './dist',
    hot: true
},
plugins: [
    new webpack.HotModuleReplacementPlugin()
]

};

我注意到如果我将加载器换成使用 react-hot,它不再知道如何读取 es6 导入:

  module: {
    loaders: [{
        test: /\.jsx?$/,
        exclude: /node_modules/,
        include: path.join(__dirname, 'src'),
        loader: 'react-hot!babel'
    }]
},

(给出错误 - 意外的标记 您可能需要一个合适的加载器来处理这种文件类型。引用导入行 )

不确定我在这里遗漏了什么,需要一些帮助。谢谢!

如果您使用的是 Babel 6.0,默认情况下它不会再转译您的代码。 (https://babeljs.io/blog/2015/10/29/6.0.0/),它说:

Since Babel is focusing on being a platform for JavaScript tooling and not an ES2015 transpiler, we’ve decided to make all of the plugins opt-in. This means when you install Babel it will no longer transpile your ES2015 code by default.

如果你想转译你的代码,你需要安装两个预设:

npm install --save-dev babel-preset-es2015 babel-preset-react

在您的 webpack.config.js 中,您可以指定使用如下预设:

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

你应该添加 .babelrc 配置文件。

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