For some reason when I run my express server on my machine it it serves the static files in my build folder without any problem, but when I deploy on Heroku I'm getting the following 404 error:
HTTP404: NOT FOUND - The server has not found anything matching the requested URI (Uniform Resource Identifier).
GET - http://playcheckerswithme.herokuapp.com/
Here's my directory structure:
.
├──index.js
├──webpack.config.js
├──package.json
├──.gitignore
├──node_modules
| ├── ...
|
├──src
| ├──assets
| | ├──index.html
| | ├──images
| | | ├──...
| |
| ├──components
| | ├──...
| |
| ├──reducers
| ├──...
|
├──build
├──index.html
├──bundle.js
├──images
├──...
And here's index.js:
var express = require('express');
var app = express();
var http = require('http').Server(app);
app.use(express.static(__dirname + '/build'))
http.listen(process.env.PORT || 3000, function(){
console.log(`listening on port: ${process.env.PORT || '3000'}`);
});
app.use(express.static(__dirname + '/build')) should be serving all static files in my build folder, but it seems that in production it isn't working correctlly. Any ideas?
Edit -
For extra context here are my package.json and webpack.config.js files
package.json
{
"name": "Checkers",
"version": "1.0.0",
"description": "react + redux + express environment for a checkers app",
"private": true,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"webpack-server": "webpack-dev-server --hot --progress --colors",
"start": "node build/index.js"
},
"keywords": [],
"author": "Nathan Jones",
"devDependencies": {
"autoprefixer-loader": "^3.1.0",
"babel-core": "^6.3.21",
"babel-loader": "^6.2.0",
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.3.13",
"babel-preset-stage-0": "^6.3.13",
"copy-webpack-plugin": "^4.0.1",
"file-loader": "^0.10.0",
"react-hot-loader": "^1.2.8",
"source-map-loader": "^0.1.5",
"url-loader": "^0.5.7",
"webpack": "^1.11.0",
"webpack-dev-server": "^1.10.1"
},
"dependencies": {
"express": "^4.15.2",
"react": "^15.4.2",
"react-dom": "^15.4.2",
"react-redux-utilities": "^1.0.7"
}
}
webpack.config.js
var { resolve } = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
function getEntrySources(sources) {
if (process.env.NODE_ENV !== 'production') {
sources.push('webpack-dev-server/client?http://localhost:8080');
sources.push('webpack/hot/only-dev-server');
}
return sources;
}
module.exports = {
entry: getEntrySources(['./src/app.js']),
output: {
filename: 'bundle.js',
path: resolve(__dirname, 'build'),
publicPath: '/'
},
devtool: 'source-map',
devServer: {
inline: true,
hot: true,
contentBase: resolve(__dirname, 'build'),
publicPath: '/'
},
module: {
preLoaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'source-map'
}
],
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loaders: ['react-hot', 'babel-loader?presets[]=es2015,presets[]=react,presets[]=stage-0'],
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract(
'style-loader',
'css-loader?sourceMap!autoprefixer?browsers=last 3 versions!sass-loader?sourceMap'
)
},
{
test: /\.(ttf|otf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
loader: 'file-loader?name=fonts/[name].[ext]'
},
{
test: /\.(png|jpg|jpeg)$/,
loader: 'url-loader'
}
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new CopyWebpackPlugin([{from: 'src/assets/', force: true}], {copyUnmodified: true})
]
};
Your npm "start" script is "node build/index.js" which means that __dirname would be pointing to <project-root>/build. You need to change your build/index.js file to use this instead since it's already in the build folder:
if (__dirname.slice(-6) === '/build') { // For production
app.use(express.static(__dirname))
} else { // For development
app.use(express.static(__dirname + '/build'))
}
Try remove slash:
app.use(express.static(__dirname + 'build'));
or use path module:
var express = require('express');
var path = require('path');
var app = express();
var http = require('http').Server(app);
app.use(express.static(path.join(__dirname, 'build')));
http.listen(process.env.PORT || 3000, function(){
console.log(`listening on port: ${process.env.PORT || '3000'}`);
});
Related
I am running my node backend on port 8000 and my dev server front end on port 9002. Ive tried a few ways to proxy to my backend when running dev, but all seem to fail (maybe because i also have
"type": "module"
)? I have tried http-proxy-middleware, but with no success.
In my server.cjs file, I have an app.get('/properties'....). It retrieves an array of objects with address, city and zip. On postman, running on port 8000, I get the correct response. Additionally, when i run start on port 8000 on my frontend, I also get the correct response. However, when I run on port 9002, my error is http://localhost:9002/properties 404, not found.
For development purposes, I need to be able to work on development, that way I wint have to run build for every UI change I make. Here is some snippets of my code below:
package.json
{
"name": "properties-three",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"proxy": "http://localhost:8000",
"scripts":
{
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack-dev-server --open --config webpack.config.cjs",
"start": "nodemon --use_strict server.mjs",
"build": "webpack --mode production"
}, "
author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.19.6",
"#babel/preset-env": "^7.19.4",
"#babel/preset-react": "^7.18.6",
"babel-loader": "^8.2.5",
"copy-webpack-plugin": "^11.0.0",
"html-webpack-plugin": "^5.5.0",
"webpack": "^5.74.0",
"webpack-cli": "^4.10.0"
},
"dependencies": {
"axios": "^1.1.3",
"cors": "^2.8.5",
"express": "^4.18.2",
"http-proxy-middleware": "^2.0.6",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.4.2",
"webpack-dev-server": "^4.11.1"
}
}
setupProxy.js
import {createProxyMiddleware} from "http-proxy-middleware";
module.exports = function(app) {
app.use(
'/api/properties',
createProxyMiddleware({
target: 'http://localhost:8000',
changeOrigin: true,
secure: false,
ws: true
})
);
};
webpack.config.cjs:
const HtmlWebPackPlugin = require("html-webpack-plugin");
const path = require('path');
const htmlPlugin = new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
});
module.exports = {
entry: "./src/index.js",
output: { // NEW
path: path.resolve(__dirname, 'dist'),
filename: "bundle.js",
publicPath: "/"
}, // NEW Ends
devServer: {
port: 9002,
static: path.join(__dirname, 'dist'),
hot: true,
historyApiFallback: true
},
resolve: {
extensions: ['.ts', ".js", ".jsx"],
},
mode: "development",
plugins: [htmlPlugin],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
]
}
};
server.mjs
import express from 'express';
import cors from 'cors';
import path from "path";
import properties from './routes/properties.routes.js'
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const PORT = 8000;
app.use(express.static(`${process.cwd()}/build`));
app.use(express.static(`${process.cwd()}/public`));
app.use(cors());
app.use(express.json());
app.use("/properties", properties);
app.use(express.static(path.join(__dirname, '/dist')));
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});
app.listen(PORT, () => console.log(`server is running on http://locahost:${PORT}`));
App.js
import React, {useState, useEffect} from "react";
import axios from "axios";
function App() {
const [properties, setProperties] = useState([]);
useEffect(() =>{
axios.get('/properties').then((response) =>{
setProperties(response.data)
})
}, []);
return (
<div className="App">Test</div>
);
}
export default App;
I have tried changing my setupProxy.js to use
import {createProxyMiddleware} from "http-proxy-middleware";
instead of
const { createProxyMiddleware } = require('http-proxy-middleware');
I have also tried changing in the component
axios.get('/properties')
to
axios.get('/api/properties')
I figured out the fix. As #NirAlfasi pointed out, I was running the BE and the FE on the same machine. Additionally, my db is currently using mock data stored within my project (for the meantime).
Within my App.js, all I needed to do was create a const baseUrl pointing to my BE port. Then in the get request on the FE, point to that baseUrl, plus the endpoint.
const baseURL = 'http://localhost:8000';
axios.get(`${baseURL}/properties`).then((response)...
I am stuck to build the node js project using webpack and I am using pug engine for front end.
My Project Structure:
bin
controller
- csv.controller.js
public
- stylesheets
- javascript
- images
routes
- csv.route.js
- index.route.js
views
- layouts
-- layout.pug
-index.pug
app.js
Package.json File
{
"name": "csv",
"version": "0.0.0",
"private": true,
"scripts": {
"build": "webpack --mode=production",
"build:dev": "webpack --mode=development",
"start":"nodemon ./app.js",
"start:dev": "webpack-dev-server --mode=development"
},
"dependencies": {
"body-parser": "^1.19.0",
"compression": "^1.7.4",
"cookie-parser": "~1.4.4",
"csv-parser": "^2.3.1",
"csv-writer": "^1.5.0",
"debug": "~2.6.9",
"express": "^4.17.1",
"express-fileupload": "^1.1.6-alpha.5",
"fast-csv": "^3.4.0",
"http-errors": "~1.6.3",
"morgan": "^1.9.1",
"multer": "^1.4.2",
"npm-check-updates": "^3.1.23",
"request": "^2.88.0"
},
"devDependencies": {
"#babel/core": "^7.6.2",
"#babel/preset-env": "^7.6.2",
"babel-loader": "^8.0.6",
"clean-webpack-plugin": "^3.0.0",
"css-loader": "^3.2.0",
"extract-text-webpack-plugin": "^3.0.2",
"file-loader": "^4.2.0",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.8.0",
"pug": "^2.0.4",
"pug-loader": "^2.4.0",
"style-loader": "^1.0.0",
"webpack": "^4.40.2",
"webpack-cli": "^3.3.9",
"webpack-dev-server": "^3.8.1",
"webpack-merge": "^4.2.2"
}
}
Actually what I want, after build, A dist folder contain a build.js or whatever its name and all public folder assets in the same directory. I tried with some below codes to build the project.
Webpack.config.js
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const config = {
entry: {
app: "./app.js"
},
target: "node",
output: {
path: path.resolve(__dirname, "dist"),
filename: "[name].bundle.js"
},
devServer: {
port: 3000
},
plugins: [
new HtmlWebpackPlugin({
template: "./views/index.pug"
})
],
module: {
rules: [
{
test: /\.pug$/,
use: ["pug-loader"]
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: ["file-loader"]
},
{
test: [/.js$/],
exclude: /(node_modules)/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-env"]
}
}
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
}
]
}
};
module.exports = (env, argv) => {
if (argv.mode === "development") {
}
if (argv.mode === "production") {
}
return config;
};
I know this question is old, but just in case somebody is looking for an answer.
You need another Webpack config for app.js, which is express entry point.
Call it webpack.server.js or webpack.server.config.js or whatever convenient. Make sure to include webpack-node-externals:
https://www.npmjs.com/package/webpack-node-externals
It may look something like this:
//webpack.server.js
const path = require('path');
const webpack = require('webpack');
const nodeExternals = require('webpack-node-externals');
module.exports = {
return ({
entry: {
app: ./src/server/app.js,
},
output: {
path: path.join(__dirname, 'dist'),
publicPath: '/',
filename: '[name].js',
},
target: 'node',
node: {
__dirname: false,
__filename: false,
},
externals: [nodeExternals()],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
},
],
},
});
};
Also use webpack-dev-middleware in your app.js.
See the below link:
https://webpack.js.org/guides/development/
In package.json include a script that looks something like this:
"server:dev": "webpack --config webpack.config.js && webpack --mode development --config webpack.server.js && node ./dist/app.js",
In your webpack.config.js make the entry point the js file that imports your front-end assets..
That is your stylesheets and any other js codes..
Not sure what css framework you are using.
But, I am using tailwindcss and I have a js entry point file that imports tailwindcss and my other js codes.
So essentially you may need two webpack config files one for the front-end and one for the express server.
Hope I am making sense.
I have created an app using Create-React-App on the client side and using express in the server side. I have created an .env file for my environment variables where the DB_USER and DB_PASSWORD will be stored.
In the server side, I would like to use a mongoose connection and the .env variables will be the credentials when connecting to the mongodb server.
I'm getting undefined variables in the terminal console when I do process.env.DB_USER. Instead I'm getting my OS environment variables, and NodeJS variables. However, I do see the variables when I do console.log(process.env.DB_USER) in chrome console/client side.
I tried to install dotenv, dotenv-webpack and configure my webpack.config but nothing seem to be working. I have also added REACT_APP_* as prefix to my variables, but still undefined values.
Also when I use dotenv and set this require('dotenv').config() in my index.js file, it complains about an fs dependency??
I just can't get the environment variables to be read in the server folder, ideally it will be nice to have these variables read in the client and server folder. Has anyone encountered this issue before? I'm just learning how to use Create-React-App and webpack. Your help will be appreciated!!!
server.js
//server.js
const express = require('express');
const path = require('path');
const router = require('./routes/routes.js')
const app = express();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const user = process.env.REACT_APP_DBUSER;
const password = process.env.REACT_APP_DBPASSWORD;
//tells express frontend will reside in client folder
app.use(express.static(path.join(__dirname, '../build')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
console.log('node', process.env);
console.log(user);//this is undefined
//connect to mongoDB
mongoose.connect(`mongodb://${user}:${password}#ds141812.mlab.com:41812/note_app_db`, { useNewUrlParser: true });
let conn = mongoose.connection;
conn.on('error', console.error.bind(console, 'connection:'));
conn.once('open', () => {
console.log('connected to database');
});
//pass in routes from router const
app.use('/',router)
module.exports=app;
webpack.config
const webpack = require('webpack');
const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const Dotenv = require('dotenv-webpack');
const config = {
entry: __dirname + '/client/js/index.jsx',
output: {
path: __dirname + '/build',
filename: 'bundle.js'
},
resolve: {
extensions: ['.js', '.jsx', '.css']
},
module: {
rules: [
{
test: /\.jsx?/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['#babel/preset-env', '#babel/react']
}
},
{
test: /\.(png|jpg|svg|gif|mp4|mov)$/,
use: [{
loader: 'file-loader',
options: {
name: '/assets/[name]-[hash:8].[ext]'
}
}]
},
{
test: /\.scss$/,
loader: 'style-loader!css-loader!sass-loader'
}
]
},
devServer: {
publicPath: '/',
contentBase: __dirname + '/build',
port: 5000,
historyApiFallback: {
index: 'index.html'
}
},
plugins: [
new CopyWebpackPlugin([
{ from: './client/index.html', to: './index.html' }
]),
new Dotenv({
path: './.env',
}),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify("development"),
REACT_APP_DBUSER: JSON.stringify(process.env.REACT_APP_DBUSER),
REACT_APP_DBPASSWORD: JSON.stringify(process.env.REACT_APP_DBPASSWORD)
}
})
]
}
module.exports = config
index.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
require('dotenv').config({path: '../../.env'});//is this how it supposed to look like???
ReactDOM.render(<App />, document.getElementById('root'));
package.json
{
"name": "note_app",
"version": "0.1.0",
"private": true,
"dependencies": {
"#babel/core": "^7.1.5",
"#babel/preset-env": "^7.1.5",
"#babel/preset-react": "^7.0.0",
"axios": "^0.18.0",
"babel-loader": "^8.0.4",
"body-parser": "^1.18.3",
"copy-webpack-plugin": "^4.6.0",
"css-loader": "^1.0.1",
"dotenv": "^6.1.0",
"dotenv-webpack": "^1.5.7",
"env-cmd": "^8.0.2",
"express": "^4.16.4",
"file-loader": "^2.0.0",
"mongoose": "^5.3.11",
"node-sass": "^4.10.0",
"nodemon": "^1.18.6",
"react": "^16.6.1",
"react-dom": "^16.6.1",
"react-modal": "^3.6.1",
"react-router-dom": "^4.3.1",
"react-scripts": "2.1.1",
"sass-loader": "^7.1.0",
"style-loader": "^0.23.1",
"webpack-cli": "^3.1.2"
},
"scripts": {
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"webpack": "webpack --mode development",
"dev": "npm run webpack && nodemon bin/www"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
]
}
.env file
REACT_APP_DBUSER="username"
REACT_APP_DBPASSWORD="password"
file structure
Found the solution, so dotenv is fine and I had uninstall dotenv-webpack. In order for the server.js file to read the environment variables, I just needed to add require('dotenv').config(); in this file. It should be good to go!
Replacing my old incorrect answer.
Rather than using that dotenv-webpack package, could you use this package:
https://www.npmjs.com/package/dotenv
In theory, you can remove that new DotEnv from your plugins and then when you call require('dotenv').config(), your webpack.config.js should have access to those env variables, then your webpack define plugin will pick them up and inject them into your code
IM SO FRUSTRATED RIGHT NOW, ive spent a whole day trying to get webpack to work, but every tutorial or documentation is terrible..it shouldnt be this hard..whats the point of these packages if they actually make you spend more time trying to configure them then saving time.
I just want the live reload to work. I've tried the inline method, iframe, hot module, the middleware with express. None of it works...Im using Node.js on atom, with safari browser.
I want it to work with express.
Can someone point me to a good tutorial...or explain step by step very simply..
Need help. please. no one every replies on these things! Thank you
GITHUB REPO LINK
webpack.config.js
const nodeExternals = require('webpack-node-externals');
module.exports =
{
entry: './app.js',
target: 'node',
externals: [nodeExternals()],
output: {
path: __dirname + '/dist',
filename: 'app.bundle.js',
},
devServer: {
port: 8000,
open: true,
inline: true
},
module: {
loaders: [
{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
}
]
}
}
package.json
{
"name": "clinic8beauty",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"b": "webpack",
"s": "webpack-dev-server",
"test": "echo \"Error: no test specified\" && exit 1"
},
"babel": {
"presets": [
"es2015"
]
},
"author": "Kosta Pontidas",
"license": "ISC",
"dependencies": {
"body-parser": "^1.17.1",
"events": "^1.1.1",
"express": "^4.15.2",
"jquery": "^3.2.1",
"pug": "^2.0.0-beta.12",
"twilio": "^2.11.1",
"validator": "^7.0.0"
},
"devDependencies": {
"babel-core": "^6.24.1",
"babel-loader": "^7.0.0",
"babel-polyfill": "^6.23.0",
"babel-preset-es2015": "^6.24.1",
"node-sass": "^4.5.2",
"pug-html-loader": "^1.1.4",
"sass-loader": "^6.0.3",
"webpack": "^2.4.1",
"webpack-dev-server": "^2.4.4",
"webpack-hot-middleware": "^2.18.0",
"webpack-node-externals": "^1.5.4"
}
}
app.js requires
const express = require('express'),
app = express(),
events = require('events'),
eventEmitter = new events.EventEmitter(),
bodyParser = require('body-parser'),
validator = require('validator'),
client = require('twilio')('AC3cdbdc7ecb720d5521f41243450343e8',
'8f76c52d839dc25aa17ddc72b3b9d781');
You have target node in your config change it to web or remove it as default is web. It should fix your problem.
Can you try the following?
const nodeExternals = require('webpack-node-externals');
const path = require('webpack'); // <== added
module.exports =
{
entry: './app.js',
// target: 'node', <== deleted
externals: [nodeExternals()],
output: {
path: path.resolve(__dirname, 'dist'), //<== added
filename: 'app.bundle.js'
},
devServer: {
port: 8000,
open: true,
inline: true,
contentBase: [path.resolve(__dirname, 'dist')/* add other directories if needed */]
},
module: {
loaders: [
{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
}
]
}
}
And run webpack-dev-server --progress instead of just webpack to start the server
Why not use nodemon globally and webpack to compile
I was planning to use ES6 Modules on front-end so I did experiment on Webpack. However, I am having a hard time making the ff: work
Hot reload when there are changes in client-side
Hot reload when there are changes in server-side (before webpack, I'm using nodemon . and not have issues with it)
Losing debug/console.log info in terminal since it's printing the webpack status and nothing on the server e.g my custom 'Server running....' log.
The setup below I was trying to run via npm start. And everytime I make any change, I have to run npm start again
package.json
{
"name": "socket-io-chat",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"start": "npm run build",
"build": "webpack -d && webpack-dev-server --hot --inline --watch && node --watch",
"build:prod": "webpack -p && webpack-dev-server"
},
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.7.1",
"express": "*",
"socket.io": "*"
},
"devDependencies": {
"babel-core": "^6.14.0",
"babel-loader": "^6.2.5",
"babel-preset-es2015": "^6.14.0",
"babel-preset-stage-2": "^6.13.0",
"nodemon": "^1.10.2",
"webpack": "^1.13.2",
"webpack-dev-server": "^1.15.1"
}
}
webpack.config.js
var path = require("path");
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var SRC_DIR = path.join(__dirname, "public");
var DIST_DIR = path.join(__dirname, "public/js/dist");
var config = {
context: __dirname,
devtool: debug ? "inline-sourcemap" : null,
entry: {
guest : path.join(SRC_DIR, "entry-guest.js"),
authenticated : path.join(SRC_DIR, "entry-authenticated.js")
},
output: {
path: DIST_DIR,
filename: "[name].js"
},
modules: {
loaders: [
{
test: /\.js?/,
include: SRC_DIR,
loader: "babel-loader",
query: {
presets: ["es2015", "stage-2"]
}
}
]
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
],
devServer: {
https: false,
contentBase: SRC_DIR,
stats: 'errors-only',
port: 3000
}
};
module.exports = config;
server.js
//create server
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());
console.log('here');
var server = require('http').createServer(app);
//prepare socket io, make it listen to server
var io = require('socket.io').listen(server);
users = [];
connections = [];
var port = process.env.PORT || 3000;
server.listen(port);
console.log(`Server running *:${port}`);
//routing
app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/index.html');
});
//open a connection
io.sockets.on('connection', function(socket) {
connections.push(socket);
console.log('Connected: %s sockets connected:', connections.length);
//...more codes here
});
In your webpack config file you can try using the plugin "Hot Module Replacement"
Along side with your already implemented Nodemon you should have both the client and server reloading on changes.
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"development"'
}
})
],
Here is an example webpack config utilizing HotModuleReplacement.
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'eval',
entry: [
'react-hot-loader/patch',
'webpack-dev-server/client?http://localhost:3001',
'webpack/hot/only-dev-server',
path.resolve(__dirname, 'client', 'index.jsx')
],
output: {
path: path.resolve(__dirname, 'public'),
publicPath: '/',
filename: 'bundle.js'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"development"'
}
})
],
resolve: {
modules: [path.resolve(__dirname, 'node_modules')],
extensions: ['*', '.js', '.jsx']
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader']
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
},
]
},
devServer: {
port: 3001,
contentBase: path.resolve(__dirname, 'public'),
hot: true,
historyApiFallback: true
},
devtool: 'source-map'
};