Express 服务器提供的 Webpack 包 - 找不到包

Webpack bundle served by express server - can't find bundle

嗨,这是我的 express 服务器,我正在尝试设置它以与 webpack 一起使用。

const Server = require('./server.js')
const path = require('path')
const port = (process.env.PORT || 3001)
const app = Server.app()

if (process.env.NODE_ENV !== 'production') {
  const webpack = require('webpack')
  const webpackDevMiddleware = require('webpack-dev-middleware')
  const webpackHotMiddleware = require('webpack-hot-middleware')
  const config = require('./webpack.config.js')
  const compiler = webpack(config)

  app.use(webpackHotMiddleware(compiler))
  app.use(webpackDevMiddleware(compiler, {
    noInfo: true,
    publicPath: path.join(__dirname, '/build')
  }))
}

app.listen(port)
  console.log(`Listening at http://localhost:${port}`)

./app.js

const path = require('path')
const express = require('express')

module.exports = {
  app: function () {
    const app = express();
    const indexPath = path.join(__dirname, '/build/index.html');
    const publicPath = express.static(path.join(__dirname, '/build'));

    app.use('/build', publicPath);
    app.get('/', function (_, res) { res.sendFile(indexPath) });

    return app;
  }
}

./server.js

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

var BUILD_DIR = path.resolve(__dirname, '/build');

var config = {
  entry: path.resolve(__dirname,'app/main.js'),
  output: {
    path: BUILD_DIR,
    filename: 'bundle.js',
    publicPath: '/build/'
  },
  module: {
    loaders: [
      { test: /\.jsx?$/, loader: 'babel-loader', exclude: /node_modules/, query: { presets: ['es2015', 'react']}},
      { test: /\.sass$/, loaders: ['style', 'css', 'sass'] },
      { test: /\.css$/, loader: "style!css" },
      { test: /\.png$/, loader: "url-loader?prefix=img/&limit=5000" },
      { test: /\.svg$/, loader: 'babel!svg-react' }
    ]
  }
};

module.exports = config;

./webpack.config.js

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>test</title>
  </head>
  <body>
    <div id="app">
      <script type="text/javascript" src="bundle.js"></script>
    </div>
  </body>
</html>

./build/index.html

当我 运行 node app.js 它找到 index.html 页面但我收到 404 错误 'cannot find bundle.js' 我确定我指向错误的目录但我似乎无法解决!

当您在 / 上提供 build/index.html 服务时,它会查找文件 /bundle.js(您启动服务器的目录),该文件显然不存在。使用您的 Webpack 配置,您将创建文件 /build/bundle.js,如果您 运行 Webpack.

现在是 webpack-dev-middleware 发挥作用的地方。它不是创建该文件,而是在命中相应路径时从内存中提供捆绑包。您需要做的就是通过在 ./app.js 中设置 publicPath 来告诉中间件您想要在 / 上提供捆绑包。

app.use(webpackDevMiddleware(compiler, {
  noInfo: true,
  publicPath: '/'
}))

您也不需要在 /build 上提供任何服务。但是如果你想用它来测试你实际文件系统中构建的包,你需要 运行 Webpack 来生成那个包。为了使其正常工作,您需要将 BUILD_DIR 更正为:

var BUILD_DIR = path.resolve(__dirname, './build');

原因是path.resolve/build当作绝对路径,并没有添加到当前目录。这也会引发权限被拒绝的错误,除非您 运行 它是根用户。有关详细信息,请参阅:https://nodejs.org/docs/latest/api/path.html#path_path_resolve_paths