首页 > 解决方案 > Express 和 Webpack 问题:“Uncaught SyntaxError: Unexpected token <”

问题描述

我无法测试我使用 WebPack 开发的反应网页。我正在尝试运行快速服务器,但我不断收到带有控制台消息的空白 localhost 页面Uncaught SyntaxError: Unexpected token <。看起来网页能够找到我的 index.html 文件,该文件又将它指向 webpack 创建的 bundle.js 文件,但由于某种原因,我相信我的 bundle.js 文件是空的?这是我第一次使用 webpack,所以我对此还是比较陌生。我将在下面发布我的目录结构、webpack.config.js文件、server.js文件和index.html文件的图片/片段。提前非常感谢你,我还是 webpack 的新手,这是我第一次尝试使用 express 和 webpack 进行实际部署。顺便说一句,我的反应应用程序运行良好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 开发工具网络结果

编辑

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

记录错误

非常感谢!

标签: javascriptnode.jsreactjsexpresswebpack

解决方案


您的 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)。

从您发布的图片来看,文件夹中没有bundle.jsdist/位置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.json scripts

"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.html放在bundle.js同一个文件夹中。


推荐阅读