【发布时间】:2020-01-25 03:41:23
【问题描述】:
我无法测试我使用 WebPack 开发的 react 网页。我正在尝试运行一个快速服务器,但我不断收到一个空白的本地主机页面,其中包含控制台消息Uncaught SyntaxError: Unexpected token <。看起来网页能够找到我的 index.html 文件,该文件又将它指向 webpack 创建的 bundle.js 文件,但由于某种原因,我相信我的 bundle.js 文件是空的?这是我第一次使用 webpack,所以我对此还是比较陌生。我将在我的目录结构下方发布图片/sn-ps,webpack.config.js 文件、server.js 文件和index.html 文件。提前非常感谢你,我还是 webpack 的新手,这是我第一次尝试使用 express 和 webpack 进行实际部署。 顺便说一句,我的 react 应用使用 webpack-dev-server 运行良好,所以不是这样。
我的目录结构
我的webpack.config.js 文件
const webpack = require('webpack');
const MomentLocalesPlugin = require('moment-locales-webpack-plugin');
module.exports = {
entry: ['babel-polyfill','./src/index.js'],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader']
},
{
test: /\.(png|jp(e*)g|svg)$/,
use: [{
loader: 'url-loader',
options: {
limit: 8000, // Convert images < 8kb to base64 strings
name: 'images/[hash]-[name].[ext]'
}
}]
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
output: {
path: __dirname + '/dist',
publicPath: '/',
filename: 'bundle.js'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new MomentLocalesPlugin()
],
devServer: {
contentBase: './dist',
hot: true
}
};
我的server.js 文件
const express = require('express');
const path = require('path');
const port = process.env.PORT || 8080;
const app = express();
app.use(express.static(__dirname));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'index.html'));
});
app.listen(port, () => {
console.log('listening on port ' + port);
console.log(__dirname);
});
我的index.html 文件
<!DOCTYPE html>
<html>
<head>
<title>Hello Webpack</title>
</head>
<body>
<div id='app'></div>
<script src="/bundle.js"></script>
</body>
</html>
开发工具网络结果
chrome dev tools network results
编辑
我的server.js 文件现在已编辑,如下所示。我已经克服了第一个错误,但现在找不到我的 bundle.js 文件?我将从下面的 git bash 终端发布日志记录错误的图片。 Chrome 开发工具控制台也给了我一个 404 错误。
const express = require('express');
const path = require('path');
const port = process.env.PORT || 8080;
const app = express();
app.use(express.static(__dirname));
app.get('*', (req, res) => {
if (req.path.endsWith('bundle.js')) {
res.sendFile(path.resolve(__dirname, 'bundle.js'));
} else {
res.sendFile(path.resolve(__dirname, 'index.html'));
}
});
/*
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'index.html'));
});
*/
app.listen(port, () => {
console.log('listening on port ' + port);
console.log(__dirname);
});
非常感谢!
【问题讨论】:
标签: javascript node.js reactjs express webpack