我有一些简单的反应代码,因为我刚刚开始学习,我认为我的开发环境可能搞砸了。这是我的代码(直接来自reactjs教程https://reactjs.org/docs/components-and-props.html):
- 的package.json:
{
"author": "Damien Bell",
"main": "main.js",
"name": "Learning",
"version": "0.0.1",
"dependencies": {
"babel-core": "^6.26.0",
"react": "^16.2.0",
"react-dom": "16.2.0",
"react-router": "4.2.0"
},
"devDependencies": {
"babelify": "^8.0.0",
"browserify": "^16.1.0",
"watchify": "^3.10.0"
},
"scripts": {
"start": "browserify -t babelify --outfile ./App.js reactive.jsx"
}
}
- reactive.jsx
import React from "react";
import ReactDOM from "react-dom";
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
ReactDOM.render(<Welcome />, document.getElementById("app") );
跑步&#34; npm start&#34;我收到以下错误:
> browserify -t babelify --outfile ./App.js reactive.jsx
SyntaxError: c:/Electron/reactive.jsx: Unexpected token (6:10)
4 | class Welcome extends React.Component {
5 | render() {
> 6 | return <h1>Hello, {this.props.name}</h1>;
| ^
7 | }
8 | }
9 |
想出来,显然babelify本身并不了解您将尝试使用jsx,而您需要指定它。还有一个奇怪的事情,如果你试图将其作为下面答案中提到的参数传递,你可能会收到一个错误说&#34;&#39; import&#39;和&#39;出口&#39;可能只出现在&#39; sourceType:module&#39;&#34;
我通过创建.babelrc文件并相应地更改我的package.json来解决这个问题:
.babelrc
{
"plugins": [ "transform-class-properties", "transform-decorators-legacy" ],
"presets": ["es2015", "react", "stage-0"]
}
的package.json
"browserify": {
"transform": [
[
"babelify"
]
]
},
"dependencies": {
"babel-core": "^6.26.0",
"react": "^16.2.0",
"react-dom": "16.2.0",
"react-router": "4.2.0"
},
"devDependencies": {
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"babel-preset-env": "^1.6.1",
"babelify": "^8.0.0",
"browserify": "^16.1.0",
"watchify": "^3.10.0"
},
"scripts": {
"start": "browserify -t babelify --outfile ./App.js reactive.jsx && electron ."
}
答案 0 :(得分:2)
发生此错误的原因是,在您当前的配置中,babelify
并不了解React的JSX语法。要解决此问题,请通过npm安装babel-preset-react
并更改您的start
脚本以包含React环境:
...
"start":"browserify -t 'babelify --presets react' --outfile ./App.js reactive.jsx"
...