我的 webpack-dev-middleware 设置无法获取/出错

Cannot GET / error with my webpack-dev-middleware setup

首先,我在这里找到了很多类似的主题,但即使参考了它们,我仍然无法完全使用它。

所以,我的问题只是在 运行 连接我的快速服务器(使用 npm run serve 之后访问 localhost:3000 时,我在 Chrome ).并不是找不到 bundle.js 文件;而是它找不到 bundle.js 文件。它根本找不到 index.html.

当我在 package.json 文件中 运行 npm run serve 脚本时,我在服务器控制台上没有看到任何错误。 Webpack 构建(从 Webpack-dev-middleware 调用)日志也没有显示错误。

如果我直接从终端 运行 webpack-dev-server 并访问相同的 URL,它可以正常工作。 (我通过 webpack.config.js 中的 devServer 选项覆盖了主机和端口以匹配我在快速服务器中使用的主机和端口。)

我做错了什么?

文件夹结构

/client
    /main.js    
/dist
    /index.html
    /assets/
/server
    /server.js
/webpack.config.js
/package.json

webpack.config.js

const path = require('path');

module.exports = {
  entry: './client/main.js',

  output: {
    path: path.resolve(__dirname, 'dist/assets'),
    filename: 'bundle.js',
    publicPath: '/assets/'
  },

  module: {
    rules: [
      {
        use: 'babel-loader',
        test: /\.jsx?$/,
        exclude: /node_modules/,
      },
      {
        use: ['style-loader', 'css-loader', 'sass-loader'],
        test: /\.scss$/
      }
    ]
  },

  devServer: {
    host: 'localhost',
    port: 3000,
    historyApiFallback: true,
    contentBase: path.resolve(__dirname, 'dist'),
  }
};

/dist/index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Webpack-Dev-Middleware Test</title>
  </head>
  <body>
    <div id="app-container">
    </div>
    <script src="/assets/bundle.js"></script>
  </body>
</html>

/server/server.js

const express = require('express');
const path =  require('path');
const app = express();
const port = process.env.PORT || 3000;

if (process.env.NODE_ENV !==  'production') {

  var webpackDevMiddleware = require("webpack-dev-middleware");
  var webpack = require("webpack");
  var config = require('./../webpack.config');
  var compiler = webpack(config);
  app.use(webpackDevMiddleware(compiler, {
    publicPath : config.output.publicPath,
  }));

} else {

  app.use(express.static(path.resolve(__dirname + '/../dist/')));
  app.get('*', (req, res) => {
    res.sendFile(path.resolve(__dirname + '/../dist/index.html'));
  });

}

app.listen(port, () => console.log('Started on port:', port));

问题是您实际上并没有在 webpack 块中的任何地方提供服务 index.html。您应该使用 html-webpack-loader 之类的插件在内存中提供服务,或者使用 express 的静态函数,我认为前者是更可取的(更多 webpack 方式)解决方案。

下面是使用html-webpack-loader的例子。

(as one of the plugins in webpack config.)

new HtmlWebpackPlugin({
  filename: 'index.html',
  template: './dist/index.html',
  title: 'Your website'
})