Webpack HMR is requesting a wrong path on an express server - express

I'm trying to set up an express server for developing a React project with hot-reload, but the HMR thing requests the wrong path for some reason and I can't fix it by changing the "publicPath" option. It requests the "public" folder even though this is the folder I server static files from, so it causes the error. How do I tweak the configuration so HMR starts working?
This is the error I see in the console:
My Webpack config:
const path = require('path');
const webpack = require('webpack');
const tsRules = {
test: /\.ts(x?)$/,
use: [
{loader: 'react-hot-loader/webpack'},
{loader: 'awesome-typescript-loader'},
]
};
const scssRules = {
test:/\.scss$/,
use: ['style-loader', 'css-loader', 'sass-loader']
};
//All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
const jsRules = {
enforce: "pre",
test: /\.js$/,
loader: "source-map-loader"
};
module.exports = {
entry: [
'./js/App.tsx',
'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000'
],
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'public'),
publicPath: '.'
},
resolve: {
extensions:['.ts','.tsx','.js', '.json']
},
module: {
rules: [
tsRules,
scssRules
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin()
],
externals: {
//"react": "React",
//"react-dom": "ReactDOM"
},
devtool: '#source-map',
}
Server.js:
import http from 'http';
import express from 'express';
import bodyParser from 'body-parser';
import openBrowser from 'react-dev-utils/openBrowser';
var webpack = require('webpack');
var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');
var config = require('../webpack.config');
var compiler = webpack(config);
const app = express();
const port = process.env.PORT || 3090;
//middleware
app.use(webpackDevMiddleware(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}));
app.use(webpackHotMiddleware(compiler,{
log: console.log,
path: '/__webpack_hmr'
}));
app.use(express.static('public'));
const server = http.createServer(app);
server.listen(port, () => {
console.log('listening on port' + port);
openBrowser(`http://localhost:${port}/`);
});

I also ran into this problem and here's how I solved it:
1) Inside webpack config, order of the "entry" configs matter, so set 'webpack-hot-middleware/client...' as the first item of the array
2) Define a public path for the middleware like so:
"webpack-hot-middleware/client?path=http://localhost:3000/__webpack_hmr"
Hope this helps!

Related

Webpack and Jquery - $ is not defined

Working first time on using Webpack in a ASP.Net Core project and running in to an issue bundling jQuery
$ is not defined
webpack.config.json
const path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const bundleFileName = 'bundle';
const dirName = 'wwwroot/dist';
module.exports = (env, argv) => {
return {
mode: argv.mode === "production" ? "production" : "development",
entry: ['./node_modules/bootstrap/dist/js/bootstrap.bundle.js', './wwwroot/js/site.js', './wwwroot/scss/site.scss'],
output: {
filename: bundleFileName + '.js',
path: path.resolve(__dirname, dirName)
},
module: {
rules: [
{
test: /\.s[c|a]ss$/,
use:
[
'style-loader',
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader',
'sass-loader'
]
}
]
},
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
}),
new CleanWebpackPlugin(),
new MiniCssExtractPlugin({
filename: bundleFileName + '.css'
})
]
};
};
I have tried and exhausted all possible variations I could find on the internet without any luck.
Using npm run build during the .Net build process to create the bundles
"$ is not defined" means that at the time when your library tried to do something with jQuery, jQuery itself either wasn't loaded or loaded incorrectly. Make sure that jQuery loads correctly first, and only then can the rest of the code use this library. Usually it is enough to put a jQuery call before all other calls.

Express.js Send Files with Hashed File Names Compiled in Webpack

This seemed pretty straightforward but I've searched a while and haven't found any solutions. If there's a better way to set this up, I'm open to suggestions.
When I change code in index.html in the below folder structure and compile with Webpack (which outputs with a new hash in filename), how do I write my Express.js route so that I don't have to change the filename everytime I compile with Webpack? Here's my setup:
Folder Structure:
root/
-dist/
--- index.1de575730aa45442d6bc.html
-src/
--- index.html
--- index.js
-webpack.static.config.js
-server/
--- server.js
Express Route:
app.get('/', (req, res) => {
res.sendFile(/*dynamically send index.[hash].html here*/);
});
webpack.static.config.js
if(process.cwd() !== __dirname) process.chdir(__dirname);
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const dotenv = require('dotenv');
const env = dotenv.config().parsed;
const definition = Object.keys(env).reduce((variables, key, i) => {
variables[key] = JSON.stringify(env[key]);
return def;
}, {});
const minify = {
collapseWhitespace: true,
keepClosingSlash: true,
removeComments: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
useShortDoctype: true
};
module.exports = {
module: {
rules: [
{ test: /\.html$/i, use: 'html-loader' },
{ test: /\.js$/i, use: 'babel-loader' },
{ test: /\.css$/i, use: ['style-loader', 'css-loader'] },
{ test: /\.(csv|tsv)$/i, use: ['csv-loader'] },
{ test: /\.xml$/i, use: ['xml-loader'] },
{ test: /\.(png|jpg|jpeg|svg|gif)$/i, type: 'asset/resource', generator: {filename: 'img/[name].[hash][ext][query]'} },
{ test: /\.(woff|woff2|eot|ttf|otf)$/i, type: 'asset/resource', generator: {filename: 'fonts/[name].[hash][ext][query]'} }
]
},
entry: {
home: './src/index.js'
},
output: {
filename: '[name].[hash].bundle.js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new webpack.optimize.ModuleConcatenationPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.DefinePlugin(definition),
new HtmlWebpackPlugin({ minify, template: path.resolve('./src/index.html'), filename: 'index.[hash].html', chunks: ['home'] })
]
};
Don't know is it still relevant, but I had the same problem recently.
Solved it with readdir method built in Node.js File System Module:
Require file system module and path module:
const path = require('path')
const fs = require('fs')
Change path to folder, where your "html" file is placed:
const pathName = path.resolve(__dirname, '../client/dist')
app.get('/', (req, res) => {
fs.readdir(pathName, (err, files) => {
if (err) {
console.error(err)
return res.status(500)
}
const filename = files.find(file => path.extname(file) === '.html')
res.sendFile(path.resolve(__dirname, '../client/dist', filename))
})
})
fs.readdir method returns array of all files in given directory, so you have to get one with ".html" extension. path.extname is method from Path Module that returns the extension of a file path.
It worked for me, but maybe there is more elegant solution.
P.S.: Or you could just remove "[hash]" from "filename" option in HtmlWebpackPlugin in webpack.static.config.js file.

Different variable value in Vue.js + Webpack in dev server vs build

I'm working on a Vue.js project which is running Webpack in local development & builds static files for deployment.
There is a variable apiDomain which needs to change from:
http://localhost.api/ - in local development
to
https://api.example.com/ - in the static build files
I've been trying to get my head around environmental variables but I'm not sure how they work in Webpack vs Vue.js.
What is the correct way to setup a Vue.js variable so it's different between local development & the static build files?
You can adapt this idea for your needs:
import axios from "axios";
const env = process.env.NODE_ENV || "development";
console.log(`we are on [${env}] environment`);
const addr = {
production: "https://rosetta-beer-store.io",
development: "http://127.0.0.1:3000",
};
const api = axios.create({
headers: {"x-api-key": "my-api-key", "x-secret-key": ""},
baseURL: addr[env],
});
export const beerservice = {
list: params => api.get("/beer/list", {params}),
find: id => api.get(`/beer/${id}`),
};
export const mediaservice = {
url: id => (id ? `${addr[env]}/media/${id}` : `${addr[env]}/icon.svg`),
};
By using the process.env.NODE_ENV (available on development and build time) you can not only to set the correct profile for the app services endpoints but also manage any tweak you need on your build scripts:
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");
const webpack = require("webpack");
module.exports = {
mode: process.env.NODE_ENV || "development",
module: {
rules: [
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
},
{
test: /\.html$/,
loader: "html-loader"
},
{
test: /\.(png|svg|jpg|gif|woff|woff2|eot|ttf|otf)$/,
use: ["file-loader"]
},
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ["babel-loader"]
}
]
},
resolve: {
extensions: ["*", ".js", ".jsx"]
},
entry: "./src/main.jsx",
output: {
filename: "build.js",
path: path.resolve(__dirname, "dist")
},
devtool:
process.env.NODE_ENV == "development" ? "inline-source-map" : undefined,
devServer: {
contentBase: "./dist",
hot: true
},
plugins: [
new CleanWebpackPlugin(["dist"]),
new HtmlWebpackPlugin({
template: "./index.html"
}),
new webpack.HotModuleReplacementPlugin()
]
};
You can see more examples on this github project, but the general idea is to take advantage of node at the build time

Why are my js files being loaded as `index.html` instead of the actual js files created by webpack?

I'm creating a simple build from webpack, using typescript, jade, and stylus. When the final index.html file is spit out, however, it seems to think the js files are just the index.html file and not the actual js files bundled up by webpack and dynamically inserted at the bottom of the html body.
My project directory structure looks like this:
- dist (compiled/transpiled files)
- server
- dependencies
- index.js
- app.js
- app.[hash].js
- polyfills.[hash].js
- node_modules
- src
- server
- dependencies
- index.ts
- app.ts
- client (ng2 ts files)
- index.jade
This is my webpack build:
'use strict';
const webpack = require('webpack');
const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const WebpackShellPlugin = require('webpack-shell-plugin');
const rootDir = __dirname;
/**
* Resolve paths so that we don't have to use relative paths when importing dependencies.
* Very helpful when scaling an application and changing the location of a file that my require another file
* in the same directory as the one it used to be in
*/
const pathResolves = [path.resolve(rootDir, 'src'), path.resolve(rootDir, 'node_modules')];
console.log('path', path.resolve(rootDir, 'src/server'));
module.exports = {
entry: {
'app': path.resolve(rootDir, 'src/client/main.ts'),
'polyfills': [
'core-js/es6',
'core-js/es7/reflect',
'zone.js/dist/zone'
]
},
output: {
path: path.resolve(rootDir, 'dist'),
filename: '[name].[hash].js'
},
module: {
rules: [
{
test: /\.component.ts$/,
use: [
{
loader: 'angular2-template-loader'
},
{
loader: 'ts-loader',
options: {
configFileName: path.resolve(rootDir, 'tsconfig.client.json')
}
}],
include: [path.resolve(rootDir, 'src/client')]
},
{
test: /\.ts$/,
use: [
{
loader: 'ts-loader',
options: {
configFileName: path.resolve(rootDir, 'tsconfig.client.json')
}
}
],
exclude: /\.component.ts$/
},
{
test: /\.jade$/,
use: ['pug-ng-html-loader']
},
{
test: /\.styl$/,
use: [
{ loader: 'raw-loader' },
{ loader: 'stylus-loader' }
]
}
]
},
resolve: {
extensions: ['.js', '.ts', '.jade', '.styl'],
modules: pathResolves
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: 'polyfills'
}),
new HTMLWebpackPlugin({
template: path.resolve(rootDir, 'dist/index.html')
}),
/**
* Define any environment variables for client
*/
new webpack.DefinePlugin({
APP_ENV: JSON.stringify(process.env.APP_ENVIRONMENT || 'development')
}),
/**
* This plugin is required because webpack 2.0 has some issues compiling angular 2.
* The angular CLI team implemented this quick regexp fix to get around compilation errors
*/
new webpack.ContextReplacementPlugin(
/angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
'./'
)
]
};
And finally, this is the src/server/app.ts file that serves up index.html:
import * as express from 'express';
import * as fs from 'fs';
import * as morgan from 'morgan';
import {
Config
}
from './dependencies/config';
export
function app(Container) {
const app = express();
const config: Config = Container.get(Config);
if (config.log.dev) {
app.use(morgan('combined'));
}
app.get('/', (req: express.Request, res: express.Response) => {
const indexPath: string = `dist/index.html`;
const encodeType: string = `utf-8`;
const html = fs.readFile(indexPath, encodeType, (err: Error, result: string) => {
if (err) {
return res.status(500).json(err);
}
return res.send(result);
});
});
return app;
}
The browser console shows the following 404 error messages (they're red in the browser console) when i go to localhost:3000:
GET http://localhost:3000/polyfills.9dcbd04127bb957ccf5e.js
GET http://localhost:3000/app.9dcbd04127bb957ccf5e.js
I know it's supposed to be getting the js files from dist/[file].[hash].js, but can't seem to make it work with webpack. Also, I should note that I set NODE_PATH to ./ in my gulp nodemon config. Any ideas why this isn't working?
Figured it out on my own. Forgot to add app.use(express.static('dist')) middleware to the app.ts file.

Correctly configure webpack-dev-middleware with vuejs project

I'm new to webpack so it's probably a stupid mistake on my part.
This is my project setup (root, atleast the relevant part):
+-- public
| |
| +-- index.html
|
+-- src
| |
| +-- App.vue
| +-- main.js
| +-- assets
|
+-- package.json
|
+-- webpack.config.js
Now I would like to use the webpack-dev(and hot)-middleware to serve my index.html and create a bundle in memory from my src folder. Now I can get the middleware set up (via the npm page) and I see the bundle gets created (through logging in console) but two things are not clear to me:
How to serve index.html
How to use the bundle thats created in memory?
Can somebody please explain how that middleware works exactly? This is my webpack config file (which is needed to plug into the middleware, it's just a copy of the webpack config file that gets created through the vue-cli):
var path = require('path')
var webpack = require('webpack')
module.exports = {
entry: './src/main.js',
output: {
path: path.resolve(__dirname, './dist'),
publicPath: '/dist/',
filename: 'build.js'
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
// vue-loader options go here
}
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
}
]
},
resolve: {
alias: {
'vue$': 'vue/dist/vue.common.js'
}
},
devServer: {
historyApiFallback: true,
noInfo: true
},
devtool: '#eval-source-map'
}
if (process.env.NODE_ENV === 'production') {
module.exports.devtool = '#source-map'
// http://vue-loader.vuejs.org/en/workflow/production.html
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
warnings: false
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true
})
])
}
I know this is probably not the correct configuration, can someone maybe point out some things?
Thanks in advance for your help!
Edit (this setup works):
My server.js now:
var express = require('express');
var logger = require('morgan');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars');
var helmet = require('helmet');
var redis = require('redis');
var redisAdapter = require('socket.io-redis');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
// use the redis adapter to create sticky sessions, this is needed because of the different clusters
io.adapter(redisAdapter( require('./app/lib/config').credentials.redis.url ));
//setup security ===============================================================
require('./app/lib/security-setup')(app, helmet);
// configuration ===============================================================
app.use(logger('dev')); // log every request to the console
// set up our express application ==============================================
// Make the body object available on the request
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//set handlebars as default templating engine
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');
// serve the static content ====================================================
if (app.settings.env === 'development') {
var webpackConfig = require('./webpack.config.js')
var compiler = require('webpack')(webpackConfig)
var devMiddleware = require('webpack-dev-middleware')(compiler, {
publicPath: webpackConfig.output.publicPath,
})
var hotMiddleware = require('webpack-hot-middleware')(compiler)
app.use(devMiddleware)
app.use(hotMiddleware)
} else {
app.use(express.static(__dirname + '/public'));
}
// set up global variables =====================================================
app.use(function(req, res, next) {
//set the io object on the response, so we can access it in our routes
res.io = io;
next();
});
// routes ======================================================================
require('./app/routes.js')(app); // load our routes and pass in our app
// export so bin/www can launch ================================================
module.exports = {app: app, server: server};
my ./bin/www:
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../server').app;
var cluster = require('cluster');
var debug = require('debug')('temp:server');
var http = require('http');
var numCPUs = process.env.WORKERS || require('os').cpus().length;
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
if (cluster.isMaster) {
// Fork workers.
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
}
// If a worker dies, log it to the console and start another worker.
cluster.on('exit', function(worker, code, signal) {
console.log('Worker ' + worker.process.pid + ' died.');
cluster.fork();
});
// Log when a worker starts listening
cluster.on('listening', function(worker, address) {
console.log('Worker started with PID ' + worker.process.pid + '.');
});
} else {
/**
* Create HTTP server.
*/
var server = require('../server').server;
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
}
// The rest of the bin/www file.....
/**
* 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);
}
My working webpack.config.js:
var path = require('path')
var webpack = require('webpack')
var HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: [
'webpack/hot/dev-server',
'webpack-hot-middleware/client',
'./src/main.js'
],
output: {
path: path.resolve(__dirname, './dist'),
publicPath: '/dist/',
filename: 'build.js'
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
// vue-loader options go here
}
},
{
test: /\.less$/,
loader: "style!css!less"
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
}
]
},
resolve: {
alias: {
'vue$': 'vue/dist/vue.common.js'
}
},
devServer: {
historyApiFallback: true,
noInfo: true
},
devtool: '#eval-source-map',
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: path.resolve(__dirname, 'public/index.html'),
inject: true
}),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
]
}
if (process.env.NODE_ENV === 'production') {
module.exports.devtool = '#source-map'
// http://vue-loader.vuejs.org/en/workflow/production.html
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
warnings: false
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true
})
])
}
How to serve index.html
To serve the index.html file you need to have a dev server running. It sounds like you are successfully doing this based on your logging of the creation of your bundle in memory. However I can't see a file for it in your set up? I've assumed another file below called: dev-server.js and it would be your entry point to serving your app, i.e. npm run dev:
package.json
"scripts": {
"dev": "node dev-server.js",
...
In webpack this dev server is generally going to be express and it's the config that you pass to your express server that will serve your index.html. As you are wanting hot-reloading you will pass express your webpack config through your middleware layers.
For hot reloading you'll need two main middlewares:
webpack-dev-middleware
webpack-hot-middleware
Then you will need to pass your config to webpack and pass your webpack compiler to the middleware, i.e.
dev-server.js
var app = require('express')()
var webpackConfig = require('./webpack.config.js')
var compiler = require('webpack')(webpackConfig)
var devMiddleware = require('webpack-dev-middleware')(compiler, {
publicPath: webpackConfig.output.publicPath,
})
var hotMiddleware = require('webpack-hot-middleware')(compiler)
app.use(devMiddleware)
app.use(hotMiddleware)
Now the key file becomes your webpack config, referenced above as: ./webpack.config.js
This leads to your next question: How to use the bundle thats created in memory?
The file you posted above looks to be about right and the key parts in regards to using the bundle are held within the output, you have:
webpack.config.js
output: {
path: path.resolve(__dirname, './dist'),
publicPath: '/dist/',
filename: 'build.js'
},
You are creating the bundle at dist/build.js relative to the current working directory. This is essentially where you need to point any references to that file within your index.html, i.e. <script src="/dist/build.js"></script>
How you do this can be manual however we'd often add a further webpack plugin to automatically build this script tag within your output html (again in this case in memory):
webpack.config.js
plugins: [
// https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: 'index.html',
template: path.resolve(__dirname, 'public/index.html'),
inject: true
}),
...
The HtmlWebpackPlugin is now essentially how you reference what the output file is called: filename and crucially where it is stored: template so if you wanted to move your index.html file this is where you tell webpack where to find it. The HtmlWebpackPlugin will now place the output 'index.html' at the publicPath referenced earlier, so to get to this file you would call /dist/index.html.
Finally you'll need some further plugins for hot reloading so your entire webpack plugins array will look like:
webpack.config.js
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
// https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'bar/index.html',
inject: true
})
]
Now we return to the dev-server.js file - or whatever yours is called that you are configuring express within - and fire up the configured express server:
dev-server.js
module.exports = app.listen(8080, function (err) {
if (err) {
console.log(err)
return
}
})
so with the above config you'd open the following uri: localhost:8080/dist/index.html