【问题标题】:Express and Webpack Problem: "Uncaught SyntaxError: Unexpected token <"Express 和 Webpack 问题:“Uncaught SyntaxError: Unexpected token <”
【发布时间】:2020-01-25 03:41:23
【问题描述】:

我无法测试我使用 WebPack 开发的 react 网页。我正在尝试运行一个快速服务器,但我不断收到一个空白的本地主机页面,其中包含控制台消息Uncaught SyntaxError: Unexpected token &lt;。看起来网页能够找到我的 index.html 文件,该文件又将它指向 webpack 创建的 bundle.js 文件,但由于某种原因,我相信我的 bundle.js 文件是空的?这是我第一次使用 webpack,所以我对此还是比较陌生。我将在我的目录结构下方发布图片/sn-ps,webpack.config.js 文件、server.js 文件和index.html 文件。提前非常感谢你,我还是 webpack 的新手,这是我第一次尝试使用 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 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);
});

logging error

非常感谢!

【问题讨论】:

    标签: javascript node.js reactjs express webpack


    【解决方案1】:

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

    从您发布的图片来看,there is no bundle.js in the dist/ folderindex.htmlserver.js 所在的位置。

    生成 bundle.js

    您必须生成捆绑包。你说,from the comments,你的 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.htmlbundle.js 放在同一个文件夹中。

    【讨论】:

    • 您好,谢谢您的回复!我刚刚尝试过,它在控制台中给了我一个 404 错误,在我的 git bash 终端中给了我另一个错误。我将在我的问题中编辑并发布上面的图片。你有没有机会知道它为什么这样做?
    • 我已经更新了答案。您应该在运行server.js 之前生成bundle.js 文件并将其放在dist/
    • 如何生成 bundle.js 文件?我总是虽然 webpack 会自动执行此操作。对不起,我知道我听起来很无知。
    • 不,你听起来一点也不无知。您是否使用create-react-app 创建了应用程序?顺便说一句,您应该将您的 server.js 恢复到其原始内容(删除我建议的 if (req.path.endsWith('bundle.js')) {,虽然它可以工作,但您的原始代码很好)。
    • 不,我没有使用 create-react-app,我是按照https://www.robinwieruch.de/minimal-react-webpack-babel-setup 的在线教程手动完成的。我会恢复的,谢谢!我认为我的webpack.config.js 文件应该在我的dist/ 文件夹中创建一个bundle.js 文件。
    猜你喜欢
    • 2017-04-08
    • 2017-06-15
    • 1970-01-01
    • 2016-06-28
    • 1970-01-01
    • 1970-01-01
    • 2017-09-10
    • 2017-03-17
    • 2012-05-17
    相关资源
    最近更新 更多