webpack + express 热更新,页面获取不到打包后的文件

发布于 2022-09-06 09:53:27 字数 6148 浏览 12 评论 0

使用webpack-dev-middleware与webpack-hot-middleware实现开发环境的热更新,进行相关的代码编写后,后台修改静态文件或者服务端代码,都可自动编译,但是浏览器一直不刷新,而且在前台页面读取打包后的资源文件时,一直报404错误,不知是否是路径写错了

webpack.config.js

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

var publicPath = '/';
var hotMiddlewareScript = 'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=10000&reload=true';

var devConfig = {
    entry: {
        index: ['./public/pages/index/index', hotMiddlewareScript]
    },
    output: {
        filename: './[name]/bundle.js',
        path: path.resolve('./public'),
        publicPath: publicPath
    },
    devtool: 'eval-source-map',
    module: {
        loaders: [{
            test: /\.(png|jpg)$/,
            loader: 'url?limit=8192&context=client&name=[path][name].[ext]'
        }, {
            test: /\.scss$/,
            loader: 'style-loader!css-loader?sourceMap!resolve-url-loader!sass-loader?sourceMap'
        }]
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoEmitOnErrorsPlugin()
    ]
};

module.exports = devConfig;

package.json

{
  "name": "node-express-demo",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "cross-env NODE_ENV=dev supervisor -w routes,views,app.js -e js,jade ./bin/www"
  },
  "dependencies": {
    "body-parser": "^1.18.2",
    "cookie-parser": "^1.4.3",
    "debug": "^2.6.9",
    "express": "^4.16.2",
    "jade": "^1.11.0",
    "morgan": "^1.9.0",
    "serve-favicon": "^2.4.5"
  },
  "devDependencies": {
    "browser-sync": "^2.18.13",
    "chokidar": "^1.7.0",
    "clean-webpack-plugin": "^0.1.17",
    "cross-env": "^3.2.4",
    "css-loader": "^0.26.4",
    "extract-text-webpack-plugin": "^2.1.2",
    "file-loader": "^0.10.1",
    "node-sass": "^4.5.3",
    "npm-install-webpack-plugin": "^4.0.5",
    "reload": "^1.1.7",
    "resolve-url-loader": "^2.2.0",
    "sass-loader": "^6.0.6",
    "style-loader": "^0.13.2",
    "url-loader": "^0.5.9",
    "webpack": "^2.7.0",
    "webpack-dev-middleware": "^1.12.2",
    "webpack-hot-middleware": "^2.21.0"
  }
}

app.js

var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var users = require('./routes/users');
var webpack = require('webpack'),
    webpackDevMiddleware = require('webpack-dev-middleware'),
    webpackHotMiddleware = require('webpack-hot-middleware'),
    webpackDevConfig = require('./webpack.config.js');

var compiler = webpack(webpackDevConfig);

var app = express();
app.locals.env = process.env.NODE_ENV || 'dev';
app.locals.reload = true;

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
//app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

// attach to the compiler & the server
app.use(webpackDevMiddleware(compiler, {

    // public path should be the same with webpack config
    publicPath: webpackDevConfig.output.publicPath,
    noInfo: true,
    reload: true,
    stats: {
        colors: true
    }
}));
app.use(webpackHotMiddleware(compiler, {
    path: '__webpack_hmr'
}));

module.exports = app;

启动express的代码

#!/usr/bin/env node

/**
 * Module dependencies.
 */

var app = require('../app');
var debug = require('debug')('node-express-demo:server');
var http = require('http');

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '8000');
app.set('port', port);

/**
 * Create HTTP server.
 */

var server = http.createServer(app);
var reload = require('reload');
reload(server, app);

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}

jade模板是这样子获取打包后文件的(路径应该不会错吧)

extends layout

block content
  h1= title
  p Welcome to #{title} #{env} #{reload}
  p(id="tip")
  script(src='/index/bundle.js')

页面报404错误
图片描述

找了很久,实在找不到原因,望各位大神解答一下

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

痴梦一场 2022-09-13 09:53:27

npm run build看看打包出来的路径是怎么样的

若言繁花未落 2022-09-13 09:53:27

var publicPath = '/';
改为'./'试一下

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文