Skip to content

Instantly share code, notes, and snippets.

@avin
Last active August 28, 2022 16:51
Show Gist options
  • Save avin/f957419b78ccc07f9b6917b8943c4e9f to your computer and use it in GitHub Desktop.
Save avin/f957419b78ccc07f9b6917b8943c4e9f to your computer and use it in GitHub Desktop.
express + webpack-dev-middleware + webpack-hot-middleware
// $/static/script.js
import './script2'
console.log('script1')
if (module.hot) {
module.hot.accept('./script2', function () {
console.log("YES")
});
}
// $/server.js
const webpack = require("webpack");
const webpackDevMiddleware = require("webpack-dev-middleware");
const webpackHotMiddleware = require("webpack-hot-middleware");
const express = require("express");
const app = express();
const path = require('path');
const compiler = webpack({
mode: "development",
entry: {
'./script1.js': ["./static/script1.js", 'webpack-hot-middleware/client'],
},
output: {
filename: '[name]',
path: path.resolve('[name]'),
publicPath: '/'
},
plugins: [
new webpack.HotModuleReplacementPlugin()
],
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: "babel-loader",
options: {
presets: ["@babel/preset-env"],
},
},
},
],
},
});
app.use(webpackDevMiddleware(compiler, {}));
app.use(webpackHotMiddleware(compiler));
app.get("/*", function(req, res) {
let file = req.path;
if(file === '/') {
file = '/index.html'
}
res.sendFile(__dirname + `/static${file}`);
});
app.listen(3000, () => console.log("Example app listening on port 3000!"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment