我看到发布的几个问题看起来很像这样,但到目前为止还没有一个解决方案有所帮助。我试图加快React的速度。我试过按照我在网上找到的每个教程,包括一些非常简单,直截了当的教程。无论我尝试什么,我都会收到意外的令牌错误。
index.js:
import React from "react";
import ReactDOM from "react-dom";
const title = 'My React page';
ReactDOM.render(
<div>{title}</div>,
document.getElementById('app')
)
的package.json:
{
"name": "swvreact",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack --mode development --display-error-details",
"build": "webpack --mode production",
"start": "webpack-dev-server --mode development --open"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.6.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-prop-types": "^0.4.0",
"webpack": "^4.3.0",
"webpack-cli": "^2.0.13",
"webpack-dev-server": "^3.1.1"
}
}
webpack.config.js:
const webpack = require('webpack');
module.exports = {
devtool: 'inline-source-map',
module: {
rules: [
{
test: /\.jsx?$/,
use: ['babel-loader']
},
{
test: /\.js?$/,
exclude: /node_modules/,
use: ['babel-loader']
}
]
},
};
.babelrc:
{
"presets": [
"env",
"react",
"es2015",
"stage-2"
]
}
错误:
ERROR in ./src/index.js
Module build failed: SyntaxError: D:/work/swvreact/swvreact/src/index.js:
Unexpected token (7:4)
5 |
6 | ReactDOM.render(
> 7 | <div>{title}</div>,
| ^
8 | document.getElementById('app')
9 | )
10 |
BabelLoaderError: SyntaxError: D:/work/swvreact/swvreact/src/index.js:
Unexpected token (7:4)
5 |
6 | ReactDOM.render(
> 7 | <div>{title}</div>,
| ^
8 | document.getElementById('app')
9 | )
10 |
at transpile (D:\work\swvreact\swvreact\node_modules\babel-
loader\lib\index.js:65:13)
我尝试过移动文件,玩配置,玩.js和.jsx文件类型,我能想到的一切。发布的代码来自我能找到的最简单的教程,似乎是最新的。
我的设置是运行Windows 10,Visual Studio Code,Chrome和Firefox以及Windows命令提示符的PC。所有申请都是最新的。我确定我错过了一些小东西,但我确定无法找到它。
答案 0 :(得分:0)
如果webpack找不到您的.babelrc
,则会出现此错误。确保文件名中没有拼写错误
您也可以尝试将babel配置放入package.json
,如下所示:
"babel": {
"presets": [
"env",
"react",
"stage-2"
]
},
或者在webpack.config.js
中添加如下选项:
test: /\.jsx?$/,
use: {
loader: 'babel-loader',
options: {
presets: [
'env',
'react',
'es2015',
'stage-2',
]
}
}