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']
}
}
],
}
评论前必须登录!
注册