【问题标题】:Express is serving up index.html instead of my Webpack bundle. Is the issue with my config file?Express 提供的是 index.html 而不是我的 Webpack 包。我的配置文件有问题吗?
【发布时间】:2021-06-05 13:30:12
【问题描述】:

我的网站无法加载,因为对 bundle.js 的请求反而返回了 index.html 文件。

这个项目是几年前的,当时它运行良好,但我正试图让它重新启动并运行,我不确定为什么现在会发生这种情况。如果有人可以提供帮助,我将不胜感激!

文件结构:

- src
  - app
  - db
  - public
     - assets (folder)
     - styles (folder)
     - index.html
  - server
     - auth (folder)
     - routers (folder)
     - server.js
- webpack.config.js

webpack.config.js:

var webpack = require('webpack');
var path = require('path');

module.exports = {
  entry: path.resolve(__dirname, 'src/app', 'client.jsx'),
  output: {
    path: path.resolve(__dirname, 'src/public/build'),
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        include: path.resolve(__dirname, 'src/app'),
        loader: 'babel-loader'
      }
    ]
  },
  devtool: 'source-map'
};

来自 index.html:

<body>
    <div id="app"></div>
    <!-- load the app scripts -->
    <script src="/build/bundle.js"></script>
</body>

来自 server.js:

app.use(express.static(path.resolve(__dirname, '../public')));

app.use('*', function (request, response){
  response.sendFile(path.resolve(__dirname, '../public', 'index.html'))
})

来自 package.json:

"scripts": {
    "start": "webpack --watch | nodemon --ignore node_modules ./src/server/server.js --exec babel-node"
},

来自 .babaelrc:

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react",
    "airbnb"
  ],
  "plugins": [
    ["@babel/plugin-proposal-decorators", { "legacy": true }],
    ["@babel/plugin-proposal-class-properties", { "loose": true }],
      "react-html-attrs",
      "transform-class-properties",
  ]
}

【问题讨论】:

  • 您能否验证public 文件夹实际上包含bundle.js 内部build?
  • @eol 呃当然。没有带有 bundle.js 的构建文件夹。所以问题是通天塔?我已经编辑了我的帖子以包含我的启动脚本和 .babelrc 文件。有什么想法有什么问题吗?
  • @monmonomon - 你找到解决办法了吗?

标签: javascript node.js express webpack


【解决方案1】:

[声誉太低无法评论]

一切看起来都很干净,所以我同意@eol 的观点,第一步是实际转译并确认构建按预期工作。

作为一个半相关的,我相信你应该将主请求处理程序中的路径解析移动为一个只被调用和解析一次的常量......可能是一个最小的收益,但就目前而言,每个请求都有解决了相同的路径。

const indexFile = path.resolve(__dirname, '../public', 'index.html');
app.use('*', function (request, response) { response.sendFile(indexFile); });

(这与第一个处理程序无关,因为解析只会在调用静态方法时发生一次。)


关于启动脚本:我认为您不想将webpack --watch 命令的输出通过管道传输到nodemon?您可能希望将 webpack 命令推送到后台运行,然后执行 nodemon。我什至认为 webpack watch 不会真正退出,所以 nodemon 永远不会被调用?

试试webpack --watch &amp; nodemon ...。

除此之外,我没有看到任何关于为什么构建无法正常工作的问题......如果你只是在终端的根目录中运行 webpack,它会编译吗?

【讨论】:

  • 是的,它不是在编译...哎呀。我已经在帖子中添加了我的启动脚本和 .babelrc 代码。你看到什么看起来不对劲了吗?感谢您的提示:路径解析!
  • @monmonomon 我编辑了答案——如果可行,请告诉我。
猜你喜欢
  • 2017-12-21
  • 2014-09-29
  • 2017-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-12
  • 2017-11-02
相关资源
最近更新 更多