Webpack dev server don't reload page when rebuild file - javascript

I'm currently trying to put my webpack-dev-server on, but when I save my file and this been rebuild correctly my page dont't reload.
I use this script for ejecute:
"start": "webpack-dev-server --mode development --host myIP --port 8080" (Also I tried with --hot --inline and didn't work too)
Here is my webpack config:
const path = require('path');
const basedir = path.join(__dirname, '../');
module.exports = {
entry: {
theme: path.join(basedir, 'assets/js', 'theme.js'),
custom: path.join(basedir, 'assets/js', 'custom.js'),
},
output: {
path: path.join(basedir, 'assets/js'),
filename: '[name]real.js'
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
}
]
}
};
And I import theme.js for example with:
<script src='http://myIP:8080/themereal.js'></script>

I tried also with hot-module-replacement and it didn't work.
After search a lot I saw in the client console the following error:
Invalid Host/Origin header client:187:9
[WDS] Disconnected!
Then I search how to fix this and found --disable-host-check option, which works to me!
"start": "webpack-dev-server --mode development --host myIP --port 8080 --disable-host-check"
I hope this will be useful for somebody more!

You need to set the watch mode. Here is an example file i recently used.
You need not to set any more attributes in dev mode.
webpack --mode development
This config is webpack 4+
const path = require('path');
const webpack = require('webpack');
const HtmlWebPackPlugin = require("html-webpack-plugin");
module.exports = (env, argv) => {
const {
mode
} = argv;
return {
module: {
entry: path.join(__dirname, 'src', 'app.js'),
watch: mode !== 'production',
output: {
path: path.join(__dirname, 'dist'),
filename: mode === 'production' ? 'bundle.min.js' : 'bundle.js'
},
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: ['babel-loader']
},
{
test: /\.less$/,
use: ['style-loader', 'css-loader', 'less-loader']
}
],
plugins: [
new HtmlWebPackPlugin({
title: 'App',
template: "./src/index.html",
filename: "./index.html"
})
]
},
devServer: {
contentBase: path.join(__dirname, 'dist')
}
};
}

Related

Source mapping with webpack for express server

I have an express server that is written in es5 and es6 combined. It consists of js and ts files. So now when I make a webpack build and start the server, it runs fine. But if my code throws an error then the error tracing is not correct i.e source of error (file, line and column number) is not showing correctly.
Is there a way to map the bundle with the source?
I have tried adding:
devTool: "source-map" to webpack config but it doesn't work, it seems to be working with the browser. Is there any way to achieve the same for server-side as well?
Here is my webpack.config.js
const nodeExternals = require("webpack-node-externals");
const webpack = require("webpack");
const path = require("path");
module.exports = {
stats: "detailed",
target: "node",
externals: [nodeExternals()],
entry: {
app: "./server.js",
backupCronApp: "./backup/cron/index.js"
},
output: {
path: path.join(__dirname, "/build"),
filename: "[name].js",
libraryTarget: "commonjs2",
},
plugins: [new webpack.EnvironmentPlugin(["NODE_ENV"])],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: "babel-loader",
},
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: ['.ts', '.js'],
},
};

WebPack output.library.type var is undefined

I am learning WebPack with a shortcode. In the code, we are trying to calculate the cube and square. They will suppose to store in a variable as per the following webpack.config.js.
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const isDevelopment = process.env.NODE_ENV === 'development';
const config = {
entry: './src/index.ts',
output: {
path: path.resolve(__dirname, 'dist'),
library: {
type: 'var',
name: 'testVar'
},
filename: '[name].js'
},
mode: 'production',
plugins: [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: "[name].css",
chunkFilename: "[id].css",
}),
new webpack.optimize.LimitChunkCountPlugin({
maxChunks: 1,
}),
new HtmlWebpackPlugin({
hash: true,
title: 'Video Player Play Ground',
myPageHeader: 'Sample Video Player',
template: './src/index.html',
filename: 'index.html'
})
],
module: {
rules: [
{
test: /\.s[ac]ss$/i,
exclude: /node_modules/,
use: [
// fallback to style-loader in development
MiniCssExtractPlugin.loader,
"css-loader",
"sass-loader",
],
},
{
test: /\.ts(x)?$/,
loader: 'ts-loader',
exclude: /node_modules/
},
{
test: /\.svg$/,
use: 'file-loader'
}
]
},
resolve: {
extensions: [
'.tsx',
'.ts',
'.js',
'.scss'
]
},
optimization: {
usedExports: true,
runtimeChunk: false,
minimize: false
}
};
module.exports = config;
As shown in the above config, we store the compiled javascript in the variable with the name "testVar".
The above approach working fine when we are using the following command line code "webpack --mode production"
In the final generated javascript file we have a line which equals to
testVar = webpack_exports;
Also, testVar.start is working fine.
But the above approach is not working when we are using the following command line "webpack serve --mode production" or "webpack serve"
When we run a local server, the testVar.start is undefined. I am not sure what I am doing wrong.
Following is the code we are using in the index.html file to call the start function, which we defined in our internal javascript
window.onload = function (){
alert(testVar);
console.log(testVar);
if(testVar.start !== undefined)
{
alert(testVar.start);
console.log(testVar.start);
testVar.start(3,2);
}
else {
alert("Start Function is undefined");
}
}
Also following is the code insight from index.ts and math.ts.
import {cube, square} from './math';
export function start(c:number, s:number) {
console.log(cube(c));
console.log(square(s));
}
export function square(x:number) {
return x * x;
}
export function cube(x:number) {
return x * x * x;
}
enter image description here
Finally, I got it working :-).
I need to add the following line in my webpack.config.js
devServer: {
injectClient: false
},
Following is the reference URL: https://github.com/webpack/webpack-dev-server/issues/2484
Don't forget to Vote it. Thanks.

Webpack bundle Node Express with hot reloading = hell

I hate to admit it, but I've been spending three long evenings trying to do - what I thought would be straightforward thing to do. I finally reached the stage where I'm fed up with it, and frankly rather frustrated because "it just won't work".
Here is what I try to achieve:
Bundle my Express server with Webpack (although my current code just renders a string in the browser, it is supposed to compile server rendered React components compiled with Babel)
Save the bundle in memory (or on disk if there is no other way)
Run webpack / dev / hot middleware to serve my Node Express app in a way that changes to the server rendered pages (which will be React components) will auto-update in the browser.
I've tried numerous combinations, tutorials that have been deprecated, npm packages that are no longer maintained and downloaded examples that just don't work.
Here is my current setup:
webpack.server.config.js:
const path = require('path');
const webpack = require('webpack');
const nodeExternals = require('webpack-node-externals');
module.exports = {
name: 'server',
mode: 'development',
target: 'node',
externals: nodeExternals(),
entry: [ './src/server/index' ],
output: {
path: path.resolve(__dirname, 'dist'),
// path: "/",
filename: '[name].js',
publicPath: '/assets/',
libraryTarget: 'commonjs2'
},
plugins: [
new webpack.HotModuleReplacementPlugin()
],
module: {
rules: [
{
test: /.js$/,
loader: 'babel-loader',
include: path.resolve(__dirname, 'src/'),
exclude: /node_modules/,
options: {
presets:
[['#babel/preset-env', { modules: 'false' }], '#babel/preset-react'],
plugins: [
['#babel/plugin-proposal-object-rest-spread', { useBuiltIns: true }],
'#babel/plugin-proposal-class-properties'
]
}
},
{
test: /\.scss$/,
loader: 'ignore-loader'
},
{
test: /\.css$/,
loader: 'ignore-loader'
},
{
test: /\.(jpg|png|svg|gif|pdf)$/,
loader: 'file-loader',
options: {
name: '[path][name].[ext]'
}
}
]
}
};
index.js:
import http from 'http';
import fs from "fs";
import express from "express";
import favicon from 'serve-favicon';
// import renderer from "./renderer";
import renderApp from './welcome';
const app = express();
app.use(favicon('./public/favicon.ico'));
app.use(express.static("public"));
if (process.env.NODE_ENV !== 'production') {
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const serverConfig = require('../../webpack.server.config');
const compiler = webpack(serverConfig);
app.use(webpackDevMiddleware(compiler, {
stats: {colors: true},
headers: { "Access-Control-Allow-Origin": "http://localhost"},
publicPath: serverConfig.output.publicPath
}));
app.use(require("webpack-hot-middleware")(compiler));
}
app.get("*", function(req, res) {
fs.readFile("./src/server/html/index.html", "utf8", function(err, data) {
const context = {};
const html = renderApp();
//const html = renderer(data, req.path, context);
res.set('content-type', 'text/html');
res.send(html);
res.end();
});
});
const PORT = process.env.PORT || 8080;
app.listen(3000);
Frankly I'm also rather confused about how this is supposed to work.
Are the following steps supposed to be executed?:
webpack webpack.server.config.js --watch
node dist/server.js // webpack output folder
Would this magically hot reload my server?
All help is welcome, or if you happened to have a working demo.
I just couldn't manage to make this work.
In the end I will also hot reload (re-render) my client bundle but I guess that will be the easy part as I've seen many, many resources about that.
Night sleep was probably needed.
I got this working (incl with React server rendered components) using StartServerPlugin.
Following setup hot reloads the Node Express server:
const path = require('path');
const webpack = require('webpack');
const nodeExternals = require('webpack-node-externals');
const StartServerPlugin = require('start-server-webpack-plugin');
module.exports = {
name: 'server',
mode: 'development',
target: 'node',
externals: nodeExternals({
whitelist: ['webpack/hot/poll?1000']
}),
entry: [ 'webpack/hot/poll?1000', './src/server/index' ],
output: {
path: path.resolve(__dirname, 'dist'),
// path: "/",
filename: 'server.js',
publicPath: '/assets/',
libraryTarget: 'commonjs2'
},
plugins: [
new StartServerPlugin({'name': 'server.js', nodeArgs: ['--inspect']}),
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.DefinePlugin({
"process.env": {
"BUILD_TARGET": JSON.stringify('server')
}
})
],
module: {
rules: [
{
test: /.js$/,
loader: 'babel-loader',
include: path.resolve(__dirname, 'src/'),
exclude: /node_modules/,
options: {
presets:
[['#babel/preset-env', { modules: 'false' }], '#babel/preset-react'],
plugins: [
['#babel/plugin-proposal-object-rest-spread', { useBuiltIns: true }],
'#babel/plugin-proposal-class-properties'
]
}
},
{
test: /\.scss$/,
loader: 'ignore-loader'
},
{
test: /\.css$/,
loader: 'ignore-loader'
},
{
test: /\.(jpg|png|svg|gif|pdf)$/,
loader: 'file-loader',
options: {
name: '[path][name].[ext]'
}
}
]
}
};
index.js:
import http from 'http'
import app from './server'
const server = http.createServer(app)
let currentApp = app;
const PORT = process.env.PORT || 8080;
server.listen(PORT);
if (module.hot) {
module.hot.accept('./server', () => {
server.removeListener('request', currentApp);
server.on('request', app);
currentApp = app;
})
}
server.js:
import http from 'http';
import fs from "fs";
import express from "express";
import favicon from 'serve-favicon';
import renderer from "./renderer";
import renderApp from './welcome';
const app = express();
app.use(favicon('./public/favicon.ico'));
app.use(express.static("public"));
app.get("*", function(req, res) {
fs.readFile("./src/server/html/index.html", "utf8", function(err, data) {
const context = {};
//const html = renderApp();
console.log('test');
const html = renderer(data, req.path, context);
res.set('content-type', 'text/html');
res.send(html);
res.end();
});
});
export default app;
Run with:
rm -rf ./dist && webpack --config webpack.server.config.js --watch
I think anwsers here are bit too complicated. It seems that Webpack does not make this easy.
Rather than trying to cook up complicated configurations, I took the issue in my own hand and created a small devserver, that does both the webpack build and server reload upon file changes. The client also has a reload logic, so the page in both cases is auto reloaded.
hot module reload for express server and webpack client
Synopsis
devserver
const fetch = require('node-fetch')
let process
function spawnserver(){
process = require('child_process').spawn("node", ["server/server.js", "dev"])
process.stdout.on('data', (data) => {
console.error(`stdout: ${data}`)
})
process.stderr.on('data', (data) => {
console.error(`stderr: ${data}`)
})
}
function rebuildsrc(){
process = require('child_process').spawn("npm", ["run", "build"])
process.stdout.on('data', (data) => {
console.error(`stdout: ${data}`)
})
process.stderr.on('data', (data) => {
console.error(`stderr: ${data}`)
})
process.on("close", code => {
console.log("build exited with code", code)
fetch("http://localhost:3000/reloadsrc").then(response=>response.text().then(content=>console.log(content)))
})
}
spawnserver()
const watcher = require("chokidar").watch("./server")
watcher.on("ready", _=>{
watcher.on("all", _=>{
console.log("server reload")
process.kill()
spawnserver()
})
})
const srcWatcher = require("chokidar").watch("./src")
srcWatcher.on("ready", _=>{
srcWatcher.on("all", _=>{
console.log("rebuild src")
rebuildsrc()
})
})
client reload
let stamp = new Date().getTime()
let lastStamp = null
app.get('/stamp', (req, res) => {
lastStamp = new Date().getTime()
res.send(`${stamp}`)
})
app.get('/reloadsrc', (req, res) => {
stamp = new Date().getTime()
res.send(`updated stamp to ${stamp}`)
})
let welcomeMessage = "Welcome !!"
let reloadScript = IS_PROD ? ``:`
let stamp = null
let reloadStarted = false
setInterval(_=>{
fetch('/stamp').then(response=>response.text().then(content=>{
if(stamp){
if(content != stamp) setTimeout(_=>{
if(!reloadStarted){
console.log("commence reload")
setInterval(_=>{
fetch(document.location.href).then(response=>response.text().then(content=>{
if(content.match(/Welcome/)){
console.log("reloading")
document.location.reload()
}
}))
}, 1000)
reloadStarted = true
}
}, 500)
}else{
if(!reloadStarted){
stamp = content
console.log("stamp set to", stamp)
}
}
}))
}, 200)
`
app.use('/dist', express.static('dist'))
app.get('/', (req, res) => {
res.send(`
<!doctype html>
<head>
<title>Reload Express Sample App</title>
</head>
<body>
<h1>${welcomeMessage}</h1>
<script>
${reloadScript}
</script>
<script src="dist/bundle.js"></script>
</body>
</html>
`)
})
Node.js, babel and webpack have been the bane of my month. There's several components that should be included. You should have a start file called "package.json"
The contents should look like:
{
"name": "react-complete-guide",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack-dev-server",
"build": "rimraf dist && webpack --config webpack.prod.config.js --progress --profile --color"
},
"author": "",
"license": "ISC",
"devDependencies": {
"autoprefixer": "^7.1.5",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-plugin-syntax-dynamic-import": "^6.18.0",
"babel-preset-env": "^1.6.0",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"css-loader": "^0.28.7",
"file-loader": "^1.1.5",
"html-webpack-plugin": "^2.30.1",
"postcss-loader": "^2.0.7",
"style-loader": "^0.19.0",
"url-loader": "^0.6.2",
"webpack": "^3.6.0",
"webpack-dev-server": "^2.9.1"
},
"dependencies": {
"react": "^16.0.0",
"react-dom": "^16.0.0",
"react-router-dom": "^4.2.2"
}
}
If you type "npm start", then the bit of code "start": "webpack-dev-server" is run. This will load a preview of the code.
To package the contents into a build you type "npm run build" and that will run the code "build": "rimraf dist && webpack --config webpack.prod.config.js --progress --profile --color". That code will run the "rimraf", which deletes the "dist" folder if it exists, the rest runs the webpack config file.
You should have two webpack files. One for hot reloads and one for packaging for the production environment. The files should be called:
"webpack.config.js" and "webpack.prod.config.js".
The contents of "webpack.config.js" look like this:
const path = require('path');
const autoprefixer = require('autoprefixer');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
devtool: 'cheap-module-eval-source-map',
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
chunkFilename: '[id].js',
publicPath: ''
},
resolve: {
extensions: ['.js', '.jsx']
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.css$/,
exclude: /node_modules/,
use: [
{ loader: 'style-loader' },
{
loader: 'css-loader',
options: {
importLoaders: 1,
modules: true,
localIdentName: '[name]__[local]__[hash:base64:5]'
}
},
{
loader: 'postcss-loader',
options: {
ident: 'postcss',
plugins: () => [
autoprefixer({
browsers: [
"> 1%",
"last 2 versions"
]
})
]
}
}
]
},
{
test: /\.(png|jpe?g|gif)$/,
loader: 'url-loader?limit=8000&name=images/[name].[ext]'
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: __dirname + '/src/index.html',
filename: 'index.html',
inject: 'body'
})
]
};
The contents of "webpack.prod.config.js" look like this:
const path = require('path');
const autoprefixer = require('autoprefixer');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
module.exports = {
devtool: 'cheap-module-source-map',
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist/new'),
filename: 'bundle.js',
chunkFilename: '[id].js',
publicPath: ''
},
resolve: {
extensions: ['.js', '.jsx']
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.css$/,
exclude: /node_modules/,
use: [
{ loader: 'style-loader' },
{
loader: 'css-loader',
options: {
importLoaders: 1,
modules: true,
localIdentName: '[name]__[local]__[hash:base64:5]'
}
},
{
loader: 'postcss-loader',
options: {
ident: 'postcss',
plugins: () => [
autoprefixer({
browsers: [
"> 1%",
"last 2 versions"
]
})
]
}
}
]
},
{
test: /\.(png|jpe?g|gif)$/,
loader: 'url-loader?limit=8000&name=images/[name].[ext]'
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: __dirname + '/src/index.html',
filename: 'index.html',
inject: 'body'
}),
new webpack.optimize.UglifyJsPlugin()
]
};
You also need a file to tell babel how to act. The file is called ".babelrc" if you are using babel. The contents look like this
{
"presets": [
["env", {
"targets": {
"browsers": [
"> 1%",
"last 2 versions"
]
}
}],
"stage-2",
"react"
],
"plugins": [
"syntax-dynamic-import"
]
}
There's a lot going on in this code. I strongly recomment watching some tutorial videos on this.

webpack error -ERROR in bundle.js from UglifyJs Unexpected token: name (urlParts)

I am starting to learn webpack. I created a simple config file:
const path = require('path');
const webpack = require('webpack');
module.exports = {
context: __dirname,
entry: './src/index.js',
output: {
filename: 'bundle.js',
publicPath: '/',
path: path.resolve(__dirname, 'dist')
},
devtool: 'inline-source-map',
devServer: {
contentBase: path.join(__dirname, 'dist'),
hot: true
},
plugins: [new webpack.HotModuleReplacementPlugin()],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
include: path.join(__dirname, 'src'),
use: ['babel-loader']
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.(png|svg|jpg|gif)$/,
use: ['file-loader']
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: ['file-loader']
}
]
}
};
Then I created src/index.js with a simple console.log('hello').
In package.json I put this:
"start": "webpack-dev-server --config webpack.config.local.js -p",
When I run "npm start" in the terminal I get this weird error:
ERROR in bundle.js from UglifyJs
Unexpected token: name (urlParts) [(webpack)-dev-server/client?http:/localhost:8080:24,0][bundle.js:4026,4]
The bundle.js looks very weird since I haven't write all this code. I googled but cannot find the solution, do you have any idea what I am doing wrong? Thanks!
Edit: I added this in .babelrc but still same error:
{"presets": ["react", "stage-2", "es2015"]}
Remove the -p from your npm script, this is why is minifying the code.
It seems that you are using webpack-dev-server and a config.local file so I assume this is only for local development, in this case the -p from webpack it's not needed.
Regarding the size of bundle.js I see you are excluding the node_modules folder, so it seems ok for me. Try to add a new script in your package.json like this:
"build": ""webpack --config webpack.config.local.js"
and see the file that will be created, so you can better understand what is going on.
Hope this help, cheers!

Webpack hot loader throws "[HMS] Hot Module Replacement is disabled."

I'm trying to build a small react tool using webpack. The following is my configuration.
var path = require('path'),
node_modules_dir = path.join(__dirname, 'node_modules');
var deps = [
'react/dist/react.min.js',
'react/dist/react.js'
];
var config = {
entry: [
path.resolve(__dirname, "app/v3.jsx"),
'./node_modules/webpack/hot/dev-server'
],
output: {
path: path.resolve(__dirname, 'dist'),
filename: "transpiled.js"
},
module: {
loaders: [
{ test: /\.jsx?$/, loader: 'babel-loader', exclude: /node_modules/ }
]
}
};
module.exports = config;
Here is my command line argument:
$ webpack-dev-server --hot --inline --progress --colors
I still see a message in the browser console saying "[HMR] Hot Module Replacement is disabled."
Needs help.
The following is the link to github issue related to this one. It still doesnt solve my problem.
Github link to this issue
Try this as your entry config. Everything else looks alright.
entry: [
'webpack-dev-server/client?http://0.0.0.0:8080',
'webpack/hot/only-dev-server',
path.resolve(__dirname, "app/v3.jsx")
]

Categories

Resources