快递和Webpack问题:“Uncaught SyntaxError:Unexpected token <”

3

我在测试使用 Webpack 开发的 React 网页时遇到了问题。我试图运行一个 express 服务器,但始终得到一个空白的本地页面,并显示控制台消息 Uncaught SyntaxError: Unexpected token <。看起来这个网页能够找到我的 index.html 文件,然后它指向由 webpack 创建的 bundle.js 文件,但出于某种原因,我认为我的 bundle.js 文件是空的?这是我第一次使用 webpack,所以我对此还比较新手。下面我将发布我的目录结构、webpack.config.js 文件、server.js 文件和 index.html 文件的图片/片段。非常感谢你的帮助,再次说明,我是新手,这是我第一次尝试使用 express 部署 webpack。顺便说一句,我的 React 应用程序使用 webpack-dev-server 正常运行,所以不是它的问题。

我的目录结构

directory-structure

我的 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开发工具网络结果

编辑

我的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);
});

日志错误

非常感谢!

1个回答

3

你的 server.js 将 index.html 提供给所有请求。

这意味着当浏览器请求 bundle.js 时,server.js 再次返回 index.html。错误来自于浏览器试图将接收到的 HTML 解析为 JavaScript 代码。

修复

你的 bundle.js 可能不在与 index.html 相同的文件夹中,否则 express 将提供它(因为有这一行:app.use(express.static(__dirname));)。

所以请仔细检查你的 bundle.js 的路径。它应该在 __dirname 中(即 ${__dirname}/bundle.js)。

根据你发布的图片,dist/ 文件夹中没有 bundle.js,而 index.htmlserver.js 则位于其中。

生成 bundle.js

您需要生成捆绑包。您说,从评论中,您的scripts是:

"scripts": {
  "start": "webpack-dev-server --config ./webpack.config.js --mode development", 
  "test": "echo \"Error: no test specified\" && exit 1"
},

要生成包,您应该添加一个build脚本并执行它。
将以下内容添加到您的package.jsonscripts:
"build": "webpack --mode production",

现在它大致是这样的:

"scripts": {
  "build": "webpack --mode production",
  "start": "webpack-dev-server --config ./webpack.config.js --mode development", 
  "test": "echo \"Error: no test specified\" && exit 1"
},

现在运行 npm run build (或 yarn build)。build.js 现在应该在 dist/ 文件夹中。
请记住,如果您要部署它,应该在提供服务时将 index.htmlbundle.js 放在同一个文件夹中。

嘿,谢谢你的回复!我刚刚尝试了一下,控制台显示了404错误,并且在我的git bash终端中出现了另一个错误。我将编辑并在我的问题中发布上面的图片。你有没有碰巧知道为什么会这样? - austinw
我已经更新了答案。在运行server.js之前,你应该生成bundle.js文件并将其放置在dist/目录下。 - acdcjunior
你能贴出你的 package.json 中的 scripts 部分吗? - acdcjunior
等一下,我看到你没有build目标脚本。你需要添加一个(在我上一条评论的指示之前,它是无法工作的),给我一分钟。 - acdcjunior
嘿,抱歉一直打扰你哈哈。但是我不知道你是否曾经使用过Heroku,但是我成功地将我的构建部署到了Heroku上,只是现在当我尝试访问网站时,它无法正常运行。我应该在我的package.json中改变其他东西吗,比如npm start之类的?--编辑-- 我相信当Heroku尝试启动一个网页时,它使用npm start,也许我需要改变我的启动脚本? - austinw
显示剩余13条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接