Javascript babel-loader jsx 语法错误:意外的令牌

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33460420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:04:58  来源:igfitidea点击:

babel-loader jsx SyntaxError: Unexpected token

javascriptreactjswebpackbabeljs

提问by Keyu Lin

I'm a beginner in React + Webpack.

我是 React + Webpack 的初学者。

I found a weird error in my hello world web app.

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

I'm using babel-loader in webpack to help me convert jsx into js, but it seems like babel can't understand jsx syntax.

我在webpack中使用babel-loader来帮我把jsx转成js,但是babel好像看不懂jsx的语法。

Here are my dependencies:

这是我的依赖项:

"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"
}

Here is my webpack.config.js

这是我的 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"}
      ]
  }
};

Here is my app/main.js

这是我的 app/main.js

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

And this is the error message

这是错误信息

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)

Thanks for you guys.

谢谢你们。

回答by Yoon

Add "babel-preset-react"

添加“babel-preset-react”

npm install babel-preset-react

and add "presets" option to babel-loader in your webpack.config.js

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

(or you can add it to your .babelrc or package.js: http://babeljs.io/docs/usage/babelrc/)

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

Here is an example webpack.config.js:

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

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

Recently Babel 6 was released and there was a major change: https://babeljs.io/blog/2015/10/29/6.0.0

最近 Babel 6 发布了,有一个比较大的变化:https: //babeljs.io/blog/2015/10/29/6.0.0

If you are using react 0.14, you should use ReactDOM.render()(from require('react-dom')) instead of React.render(): https://facebook.github.io/react/blog/#changelog

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

UPDATE 2018

2018 年更新

Rule.query has already been deprecated in favour of Rule.options. Usage in webpack 4 is as follows:

Rule.query 已经被弃用,取而代之的是 Rule.options。webpack 4 中的用法如下:

npm install babel-loader babel-preset-react

Then in your webpack configuration (as an entry in the module.rules array in the module.exports object)

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

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

回答by svnm

I ran into a similar issue when migrating from babel 5 to babel 6.

从 babel 5 迁移到 babel 6 时,我遇到了类似的问题。

I was just running babel to compile the srcto libfolder babel src --out-dir lib

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

I will share my setup for babel 6:

我将分享我的 babel 6 设置:

Ensure you have the following babel 6 devDependenciesinstalled

确保您有以下巴贝尔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"

Add your .babelrcfile to the project:

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

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

回答by Everett

Since the answer above still leaves some peoplein the dark, here's what a complete webpack.config.js might look like:

由于上面的答案仍然让一些人一头雾水,因此完整的 webpack.config.js 可能如下所示:

var path = require('path');
var config = {
    entry: path.resolve(__dirname, 'app/main.js'),
    output: {
        path: path.resolve(__dirname, 'build'),
        filename: 'bundle.js'
    },
    module: {
        loaders: [{
            test: /\.jsx?$/,
            loader: 'babel',
            query:
            {
                presets:['es2015', 'react']
            }
        }]
    },

};

module.exports = config;

回答by albanx

For me the solution was to create the file .babelrcwith this content:

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

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

回答by Vladyslav Babenko

The following way has helped me (includes react-hot, babel loaders and es2015, react presets):

以下方法对我有所帮助(包括 react-hot、babel 加载器和 es2015、react 预设):

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

回答by Aftab Naveed

For those who still might be facing issue adding jsx to test fixed it for me

对于那些仍然可能遇到问题的人,添加 jsx 来测试为我修复了它

test: /\.jsx?$/,

回答by jose920405

This works perfect for me

这对我来说很完美

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

回答by Maxime Brehin

You can find a really good boilerplate made by Henrik Joreteg (ampersandjs) here: https://github.com/HenrikJoreteg/hjs-webpack

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

Then in your webpack.config.js

然后在你的 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
})