由快递服务器提供的Webpack捆绑包 - 无法找到捆绑包

时间:2017-02-13 12:13:16

标签: javascript node.js express webpack webpack-dev-server

嗨,这是我的快递服务器,我试图设置与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>

./建立/ index.html中

当我运行node app.js时,它会找到index.html页面,但我收到404错误&#39;找不到bundle.js&#39;我确定我指向错误的目录,但我似乎无法解决它!

1 个答案:

答案 0 :(得分:1)

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

现在这里是webpack-dev-middleware所在的位置。无论何时创建该文件,只要命中相应的路径,它就会从内存中提供服务。您需要做的就是通过在 ./ app.js 中设置/,告诉中间件您要在publicPath上投放捆绑包。

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

您也不需要在/build上投放任何内容。但是,如果要使用它来测试实际文件系统中构建的bundle,则需要运行Webpack来生成该bundle。为了使其正常工作,您需要将BUILD_DIR更正为:

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

原因是path.resolve/build视为绝对路径,并且不会将其添加到当前目录。除非您以root身份运行,否则还会抛出权限被拒绝错误。有关详细信息,请参阅:https://nodejs.org/docs/latest/api/path.html#path_path_resolve_paths