我一直在为此而自杀,但无济于事。 我正在使用ReactJS和Babel。我安装了节点JS以及webpack。 这是一个简单的Hello World应用程序。 我得到的错误是:
未捕获的SyntaxError:意外的令牌导入
以下是源代码:
的package.json
{
"name": "app",
"version": "1.0.0",
"main": "webapp.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-preset-react": "^6.3.13",
"express": "^4.15.3",
"react": "^15.5.4",
"react-dom": "^15.5.4"
},
"devDependencies": {
"babel-cli": "^6.24.1",
"babel-core": "^6.24.1",
"babel-loader": "^7.0.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"webpack": "^2.5.1"
},
"description": ""
}
webpack.config.js
var path = require('path');
module.exports = {
entry: './webapp.js',
output: {
path: './',
filename: 'index.js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
webapp.js
var express = require('express')
var app = express();
app.use(express.static('static'));
var server = app.listen(3000, function() {
var port = server.address().port;
console.log("Started server at port", port);
});
的index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React!</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.3/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.3/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/javascript" src="App.js">
</script>
</body>
</html>
App.js
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);
答案 0 :(得分:0)
您的网络包已配置为构建webapp.js
来源。这是服务器端节点应用程序。所以加上这个:
target: "node"
到你的webpack配置。
此选项启用node
构建环境。
要构建客户端应用程序,您需要另一个配置。 webpack配置必须
target: "web"
entry: './App.js',
你的HTML必须有:
<script type="text/javascript" src="index.js">
而不是
<script type="text/javascript" src="App.js">
因为浏览器无法理解现代语法。你需要构建和加载已编译的js包。
答案 1 :(得分:0)
要添加到秋葵提到的内容中,
我注意到您有:
test: /\.js$/,
相反,您应该具有:
test: /\.jsx?/,
(因为react预设正在寻找jsx以便将其转换为js)
如果更改之后您仍然遇到问题,我建议使用npm i -D最新的babel预设,如下所示:
module.exports = {
mode: 'development',
target: 'web',
entry: `${SRC_DIR}\\app.jsx`,
output: {
filename: CHANGE_ME,
path: DIST_DIR
},
module: {
rules: [
{
test: /\.jsx?/,
include: SRC_DIR,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['@babel/preset-react', '@babel/preset-env']
}
},