5

首先,我在这里发现了许多类似的主题,但即使参考了它们,我仍然无法让它发挥作用。

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

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

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

我究竟做错了什么?

文件夹结构

/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));
4

1 回答 1

3

问题是你并没有真正index.html在 webpack 块中的任何地方提供服务。您应该使用插件(例如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'
})
于 2017-05-30T04:05:19.433 回答