【问题标题】:Unexpected token - React babel意外的令牌 - React babel
【发布时间】:2016-07-01 14:49:54
【问题描述】:

我是新来的世界反应,我有一个错误,不会让我进步。这是我的 webpack

module.exports = {
entry: [
'./src/index.js'
],
output: {
path: __dirname,
publicPath: '/',
filename: 'bundle.js'
},
module: {
 loaders: [{
  exclude: /node_modules/,
  loader: 'babel'
 }]
}
resolve: {
 extensions: ['', '.js', '.jsx']
},
devServer: {
 historyApiFallback: true,
 contentBase: './'
}
};

这是我的代码 js

import React from 'react';
import ReactDOM from 'react-dom';

import SearchBar from './components/search_bar';

const API = '';

const App = () => {
 return (
     <div>
         <SearchBar />
     </div>
 );
}

ReactDOM.render(<App />, document.querySelector('.container'));

这是错误 https://gyazo.com/be83135be6f0e7b8ca0c2852536c792f

我尝试了这个解决方案,但它不起作用 babel-loader jsx SyntaxError: Unexpected token

这是一个项目https://github.com/jmrosdev/Practicas/tree/master/React/youtube-search

再见,谢谢!

【问题讨论】:

标签: javascript reactjs babeljs


【解决方案1】:

失败是因为 Babel 无法识别 JSX 语法。所以你需要安装一两个 babel 预设:

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

如果您还没有 .babelrc 文件,请在项目的根目录下创建一个。它应该有这个内容

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

【讨论】:

  • 我喜欢添加一个简单的根文件修复奇怪的错误 :) 谢谢!
  • 奇怪的是我运行 npm start 一段时间没有问题,然后开始出现这个错误。幸运的是,您的修复对我有用。
【解决方案2】:

我遇到了同样的错误,原因是 type="text/babel" 丢失了:

 <script src="./index.js" type="text/babel"></script>

【讨论】:

    【解决方案3】:

    你很可能没有使用 babel-react 预设。

    确保你的依赖项中有它,在你的 package.json 文件中(如果你没有它,请在 npm install babel-core babel-preset-es2015 babel-preset-react -D )和 webpack.config.jsloaders 部分中创建此行

        module: {
         loaders: [{
          exclude: /node_modules/,
          loader: 'babel'
         }]
        }
    

    进入这个

    module: {
     loaders: [{
      exclude: /node_modules/,
      loader: 'babel'
     },
    {
            test: /\.js$/,
            loader: 'babel-loader',
            query: {
              presets: ['es2015', 'react']
            }
    
    }]
    

    【讨论】:

      猜你喜欢
      • 2016-07-10
      • 1970-01-01
      • 1970-01-01
      • 2020-11-16
      • 2016-11-28
      • 1970-01-01
      • 2019-09-16
      • 2017-05-08
      • 2016-02-12
      相关资源
      最近更新 更多