babel-loader jsx SyntaxError: 予期しないトークン [重複] 質問する

babel-loader jsx SyntaxError: 予期しないトークン [重複] 質問する

私はReact + Webpackの初心者です。

Hello World Web アプリで奇妙なエラーが見つかりました。

私は jsx を js に変換するために webpack で babel-loader を使用していますが、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)

皆さんありがとう。

ベストアンサー1

「babel-preset-react」を追加

npm install babel-preset-react

そして、webpack.config.jsのbabel-loaderに「presets」オプションを追加します。

(または、.babelrc または package.js に追加することもできます:詳しくはこちら

以下は 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/#変更ログ

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']
        }
      }
    ],
  }

おすすめ記事