我按照frontendmasters.com上的教程进行操作,并尝试简化其中一个设置。我输入yarn build
时会看到以下错误,我认为这是因为在运行webpack之前babel没有删除JSX:
ERROR in ./js/ClientApp.jsx
Module build failed: SyntaxError: Unexpected token (5:25)
3 | import { BrowserRouter, Route, Switch } from 'react-router-dom';
4 |
> 5 | const HelloWorld = () => <h1>Hello World!</h1>;
| ^
6 |
7 | const App = () => (
8 | <BrowserRouter>
纱线构建的package.json
为:
{
"scripts": {
"format": "prettier --list-different --single-quote --print-width=120 webpack.config.js \"js/**/*.{js,jsx}\"",
"lint": "eslint **/*.{js,jsx} --quiet",
"watch": "webpack --watch",
"build": "webpack -p",
"build:dev": "webpack -d"
},
"name": "foobar",
"version": "1.0.0",
"description": "",
"main": "",
"repository": "",
"author": "",
"license": "MIT",
"dependencies": {
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-redux": "^5.0.7",
"react-router-dom": "^4.2.2",
"redux": "^3.7.2",
"webpack": "^3.11.0"
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-eslint": "^8.2.1",
"babel-loader": "^7.1.2",
"eslint": "^4.18.0",
"eslint-config-prettier": "^2.9.0",
"eslint-config-react": "^1.1.7",
"eslint-loader": "^1.9.0",
"eslint-plugin-flow": "^2.29.1",
"eslint-plugin-flowtype": "^2.44.0",
"eslint-plugin-jsx-a11y": "^6.0.3",
"eslint-plugin-prettier": "^2.6.0",
"eslint-plugin-react": "^7.6.1",
"prettier": "^1.10.2"
}
}
我的webpack.config.js是:
const path = require('path');
const webpack = require('webpack');
module.exports = {
context: __dirname,
entry: "./js/ClientApp.jsx",
devtool: "cheap-eval-source-map",
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js'
},
resolve: {
extensions: ['.js', '.jsx', '.json']
},
stats: {
colors: true,
reasons: true,
chunks: true
},
module: {
rules: [
{
test: /\.jsx?$/,
loaders: 'babel-loader',
}
]
}
}
我的js/ClientApp.jsx
只是一个简单的语法上有效的文件,我已经遗漏了,因为StackOverflow已经在抱怨这条消息主要是代码。
有没有人知道我做错了什么以及为什么babel没有正确处理JSX?
答案 0 :(得分:1)
看起来Babel尚未配置为正确转换您的代码。
鉴于您使用es2015
+ React JSX
语法,快速方法包括安装Babel的ES2015 preset和React preset作为dev依赖项并配置您的{{1文件使用它们:
.babelrc
如果你想微调你的babel设置,你可以考虑只安装你实际需要的Babel 插件而不是上面提到的预设(这只是一组Babel插件),