Reputation: 1446
I'm making MERN (with React in Front-end and Express in Back-end) based application from a scratch. And I want webpack to reload page every time I save files. But it's not working.
My webpack.config.js
const path = require('path');
const entryFile = path.resolve(__dirname, 'src', 'client', 'app.js');
const outputDir = path.resolve(__dirname, 'public');
module.exports = {
entry: ['babel-polyfill', entryFile],
output: {
filename: 'bundle.js',
path: outputDir
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.(scss|css)$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader',
},
{
loader: 'sass-loader'
}
]
}
]
}
};
my package.json
{
...
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "babel-node src/server/app.js",
"prestart": "webpack --mode development"
},
"repository": {
"type": "git",
"url": "git+https://github.com/2u4u/share-book.git"
},
...
"dependencies": {
"express": "^4.16.3",
"webpack": "^4.17.1",
"webpack-dev-server": "^3.1.5"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"css-loader": "^1.0.0",
"node-sass": "^4.9.3",
"react": "^16.4.2",
"react-dom": "^16.4.2",
"sass-loader": "^7.1.0",
"style-loader": "^0.22.1",
"webpack-cli": "^3.1.0",
"webpack-command": "^0.4.1"
}
}
I tried to add watch: true
in the end of webpack config, but it's not starting server then. Where is the problem?
UPD: Can problem be in server/app.js?
import express from 'express';
import path from 'path';
const app = express();
const publicPath = path.resolve(__dirname, '..', '..', 'public');
app.use(express.static(publicPath));
app.listen(3000, () => {
console.log(`NEW one MERN Boilerplate listening on port 3000 and looking in folder ${publicPath}`);
});
Upvotes: 1
Views: 312
Reputation: 6841
"prestart": "webpack --mode development --watch"
Simple and easy. This has to be ran into one terminal, the server in another one.
Upvotes: 0
Reputation: 8102
Add -- hot
in your dev script it should work if you’re using webpack v4. Otherwise you can add hot module in your webpack config.
The following should be your devDependencies
"dependencies": {
"webpack": "^4.17.1",
"webpack-dev-server": "^3.1.5"
},
and make changes in your "start and "prestart" script:
"prestart": webpack-dev-server --mode development --config webpack.config.js --open --hot
"start": "babel-node nodemon src/server/app.js",
Upvotes: 1
Reputation: 33994
You can directly add watch to prestart script in package.json
"prestart": "webpack --mode development" --watch --hot
OR
add devserver in webpack.config.js file something like below
devServer: {
contentBase: './public',
hot: true,
watch: true
}
Upvotes: 1