webpack babel-loader将jsx转换为js错误(build failed SyntaxError ~main.js Unexpected token)
【webpack babel-loader将jsx转换为js错误(build failed SyntaxError ~main.js Unexpected token)】React+Webpack,在webpack中使用babel-loader将jsx转换为js错误,错误信息如下:
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)
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"}
]
}
};
解决办法如下:
添加babel-preset-react:
npm install babel-preset-react
然后在webpack.config.js中添加presets选项到babel-loader,或也可以添加到.babelrc或package.js,参考:https://babeljs.io/docs/en/config-files/。下面是webpack.config.js的配置:
{
test: /\.jsx?$/,//同时匹配.js和.jsx文件
exclude: /node_modules/,
loader: "babel",
query:
{
presets:['react']
}
}
特别注意,Webpack4使用如下方式:
npm install babel-loader babel-preset-react
webpack配置如下:
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['react']
}
}
],
}
推荐阅读
- webpack和babel出错(You may need an appropriate loader to handle this file type.)
- webpack和babel项目使用ES6装饰器错误(Decorators are not supported yet in 6.x pending proposal update.)
- AdSense申请失败解决办法(我们发现,您还有一个 AdSense 帐号。每位用户只能拥有一个帐号。要使用此帐号,请关闭另一个帐号。)
- JS如何实现二叉堆(JavaScript实现最小二叉堆和优先队列)
- JavaScript常用数据结构之线性表(数组和链表)
- 数组和链表有什么区别(哪个更快?有什么优缺点?有哪些应用场景?)
- JavaScript常用数据结构(栈(Stack)详解)
- JavaScript基本数据结构(队列基本原理和实现)
- 倒排索引(反向索引)详细介绍