gpt4 book ai didi

html - (ReactJS、Babel、Webpack、NodeJS) 未捕获的语法错误 : Unexpected token import

转载 作者:太空宇宙 更新时间:2023-11-04 02:06:29 25 4
gpt4 key购买 nike

我已经为此自杀了好几天,但毫无结果。我正在使用 ReactJS 和 Babel。我安装了 Node JS 和 webpack。这是一个简单的 Hello World 应用程序。我得到的错误是:

Uncaught SyntaxError: Unexpected token import

这是源代码:

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')
);

最佳答案

您的 webpack 配置为构建 webapp.js 源。这是服务器端 Node 应用程序。所以添加这个:

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 包。

关于html - (ReactJS、Babel、Webpack、NodeJS) 未捕获的语法错误 : Unexpected token import,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44087404/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com