Webpack-dev-server is not detecting file changes - reactjs

I have a react app setup with webpack and babel. I'm trying to enable hmr from webpack which seems to work fine except that it does not recompile when I change any file under /src/ . Changing package.json does seem to be detected and forces a recompile but the changes under /src/ are still not detected even after the recompile. My webpack.config is below:
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: {
main: './src/index.js',
},
output: {
path: path.join(__dirname, 'dist'),
publicPath: '/',
filename: 'bundle.js',
},
devServer: {
hot: true,
contentBase: './public/',
publicPath: '/',
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
include: path.join(__dirname),
use: ['babel-loader'],
},
],
},
plugins: [new webpack.HotModuleReplacementPlugin()],
};

Related

webpack options has an unknown property 'hotOnly'. Invalid options object. Dev Server has been initialized using an options object

I am running the command npx webpack-dev-server --mode development in my react application and getting the preceding error.
[webpack-cli] Invalid options object. Dev Server has been initialized using an options object that does not match the API schema.
- options has an unknown property 'hotOnly'. These properties are valid:
Below is my webpack.config.js file.
const path = require("path");
const webpack = require("webpack");
module.exports = {
entry: "./src/index.js",
mode: "development",
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules)/,
loader: "babel-loader",
options: {
presets: ["#babel/env"],
},
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
},
],
},
resolve: {
extensions: ["*", ".js", ".jsx"],
},
output: {
path: path.resolve(__dirname, "dist/"),
publicPath: "/dist/",
filename: "bundle.js",
},
devServer: {
contentBase: path.join(__dirname, "public/"),
port: 3000,
publicPath: "https://localhost:3000/dist/",
hotOnly: true,
},
plugins: [new webpack.HotModuleReplacementPlugin()],
};
Any idea what is causing this issue?
So devServer|Webpack config is related to Options for webpack-dev-server
If your webpack is using webpack-dev-server version 4 you should use this migration guide
// your v3 config
devServer: {
contentBase: path.join(__dirname, "public/"),
port: 3000,
publicPath: "https://localhost:3000/dist/",
hotOnly: true,
},
in v4 will be
devServer: {
// contentBase
static : {
directory : path.join(__dirname, "public/")
},
port: 3000,
// publicPath
devMiddleware:{
publicPath: "https://localhost:3000/dist/",
}
// hotOnly
hot: "only",
},
It seems like the updated version of webpack doesn't support the property hotOnly, we should use the option hot instead. You can see a GitHub issue associated with this here.
devServer: {
hot: "only", // hot:true
},
The latest versions automatically apply HotModuleReplacementPlugin plugin when you set hot: true, so please check you don't have HotModuleReplacementPlugin in your plugins if you have hot: true/hot: "only". You will get a warning as " [webpack-dev-server] "hot: true" automatically applies HMR plugin, you don't have to add it manually to your webpack configuration." if you have the preceding settings.
plugins: [new webpack.HotModuleReplacementPlugin()],
If you are getting error "static heartbeatInterval = 1000; SyntaxError: Unexpected token =", make sure to use the node version is >= 12.13.0 as per the guide here.
If everything is done, you should be able to see an output as preceding when you run npx webpack-dev-server --mode development.
Thanks, #Tushar Mistry for providing the migration guide.
Below is my completed webpack.config.js file.
const path = require("path");
const webpack = require("webpack");
module.exports = {
entry: "./src/index.js",
mode: "development",
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules)/,
loader: "babel-loader",
options: {
presets: ["#babel/env"],
},
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
},
],
},
resolve: {
extensions: ["*", ".js", ".jsx"],
},
output: {
path: path.resolve(__dirname, "dist/"),
publicPath: "/dist/",
filename: "bundle.js",
},
devServer: {
static: {
directory: path.join(__dirname, "public/"),
},
port: 3000,
devMiddleware: {
publicPath: "https://localhost:3000/dist/",
},
hot: "only",
},
};
Or you can also use the old version as below.
"webpack": "4.41.5",
"webpack-cli": "3.3.10",
"webpack-dev-server": "3.10.1"
For me, comma was missing after devMiddleware property causing error.
Solved by installing an older version of webpack
"webpack-dev-server": "3.10.1"

Entrypoint undefined = ./index.html

Hi I'm a fairly new programmer in webpack, I am trying to create react app using webpack. but i am getting this error.
Error
Child html-webpack-plugin for "index.html":
1 asset
Entrypoint undefined = ./index.html
webpack.config.js
[![const HtmlWebPackPlugin = require("html-webpack-plugin");
const path = require('path')
const htmlPlugin = new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
});
module.exports = {
entry: "index.js",
output: {
path: path.resolve('dist'),
filename: 'bundle.js'
},
module: {
rules: \[
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
"presets": \["env", "react"\]
}
}
}
\]
},
plugins: \[htmlPlugin\],
devServer: {
contentBase: './dist',
hot: true
}
};
This is My Project structure
[https://i.stack.imgur.com/ve1oa.png]
Maybe filename: "./index.html" should be filename: "index.html" ?
Or just remove it
Seems like this error message is harmless and can be ignored: html-webpack-plugin issue #895

Hot reloald webpac-dev-server when changing sass

i have simple webpack build with webpack-dev-server. It's work, and when i changing .js file its autorefreshingin browser. But when i changhing .sass nothing happens. Here is my webpack.confing
const { resolve } = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const OpenBrowserPlugin = require('open-browser-webpack-plugin');
const config = {
devtool: 'cheap-module-eval-source-map',
entry: [
'react-hot-loader/patch',
'webpack-dev-server/client?http://localhost:8080',
'webpack/hot/only-dev-server',
'./main.js',
'./assets/sass/main.sass',
],
output: {
filename: 'bundle.js',
path: resolve(__dirname, 'dist'),
publicPath: '/',
},
context: resolve(__dirname, 'app'),
devServer: {
hot: true,
contentBase: resolve(__dirname, 'dist'),
publicPath: '/',
},
module: {
rules: [
{
test: /\.js$/,
loaders: [
'babel-loader',
],
exclude: /node_modules/,
},
{
test: /\.sass$/,
exclude: /node_modules/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
'css-loader',
{
loader: 'sass-loader',
query: {
sourceMap: false,
},
},
],
}),
},
{ test: /\.(png|jpg)$/, use: 'url-loader?limit=15000' },
{ test: /\.eot(\?v=\d+.\d+.\d+)?$/, use: 'file-loader' },
{ test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, use: 'url-loader?limit=10000&mimetype=application/font-woff' },
{ test: /\.[ot]tf(\?v=\d+.\d+.\d+)?$/, use: 'url-loader?limit=10000&mimetype=application/octet-stream' },
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, use: 'url-loader?limit=10000&mimetype=image/svg+xml' },
]
},
plugins: [
new ExtractTextPlugin({ filename: 'style.css', disable: false, allChunks: true }),
new CopyWebpackPlugin([{ from: 'vendors', to: 'vendors' }]),
new OpenBrowserPlugin({ url: 'http://localhost:8080' }),
new webpack.HotModuleReplacementPlugin(),
],
};
module.exports = config;
Also, please tell me how to make the files get in the right folders during the build (.css to dist/css, js to dist/js), 'cuz rigth now they all go to the root of dest folder.
Hot reloading doesn't work with extract-text-webpack-plugin. You should not use it in development and you can easily disable it by setting the disable option to true in development. You can use an environment variable like so:
new ExtractTextPlugin({
filename: 'style.css',
disable: process.env.NODE_ENV !== 'production',
allChunks: true
}),
This will only extract the CSS in production mode, so you'd need to run your production build with:
NODE_ENV=production webpack [options]
Or if you are on windows:
set NODE_ENV=production && webpack [options]
There is also cross-env if you look for a cross platform solution.
For getting the JavaScript files to dist/js and the CSS file to dist/css you could set output.path to dist/js and then tell extract-text-webpack-plugin to generate the file into ../css/style.css.
output: {
filename: 'bundle.js',
path: resolve(__dirname, 'dist/js'),
publicPath: '/',
},
plugins: [
new ExtractTextPlugin({
filename: '../css/style.css',
disable: process.env.NODE_ENV !== 'production',
allChunks: true
}),
// other plugins
]

Can't see background image running webpack

I am recently learning React and have problem setting webpack. I wrote a background image in sass file but I can't see this image in browser, I checked the develope tool and saw a strange file name as the attatched picture shows. There's no error when I run webpack. I think I might set the webpack.config.js incorrectly. Can somebody take a look for me? here's the source code:
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: [
'eventsource-polyfill',
'./src/index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/'
},
module: {
loaders: [
{
test: /.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
},
{
test: /\.sass$/,
loader: 'style!css?sourceMap!sass'
},
{
test: /\.(jpg|gif|png)$/,
loader: "file"
},
{
test: /\.(jpg|gif|png)$/,
loader: "url"
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, 'src', 'index.html'),
filename: 'index.html',
inject: 'body',
})
]
};
I also put my files on github: https://github.com/john650914/ReactQuestion.git
Thank you very much~~~~~~~~~
Webpack will start looking for your url path at '/' which was set by your publicPath in your webpack.config.js
Looking at your repository with your link provided:
https://github.com/john650914/ReactQuestion.git
It seems like your image isn't in your projects root. You should specify the correct publicPath that leads to where you store your assets. So for example if you stored your images in /src/assets/ then your publicPath should be ./src/assets/ like this:
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: './src/assets/'
},

Webpack server configuration + external libs

I have the following webpack configuration file:
const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const LiveReloadPlugin = require('webpack-livereload-plugin');
const path = require('path');
module.exports = {
entry: [
'webpack-dev-server/client?http://0.0.0.0:2000', // WebpackDevServer host and port
'webpack/hot/only-dev-server', // "only" prevents reload on syntax errors
'./app/index.tsx'
],
output: {
path: __dirname + '/dist/',
filename: 'bundle.js'
},
devtool: 'source-map',
resolve: {
extensions: ['', '.webpack.js', '.web.js', '.ts', '.tsx', '.js']
},
module: {
loaders: [
{
test: /\.tsx?$/,
loaders: ['react-hot', 'ts'],
include: path.join(__dirname, 'app')
}
],
preLoaders: [
'source-map-loader'.
{test: /\.js$/, loader: 'source-map-loader'}
]
},
plugins: [
new CopyWebpackPlugin([
{from: './app/index.html', to: './dist/index.html'}
]),
new webpack.HotModuleReplacementPlugin()
],
builds.
externals: {
'react': 'React',
'react-dom': 'ReactDOM'
}
};
and here is my server configuration:
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const config = require('./webpack.config');
new WebpackDevServer(webpack(config), {
contentBase: './dist',
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: true,
open: 'http://localhost:2000'
}).listen(2000, 'localhost', function (err, result) {
if (err) {
return console.log(err);
}
console.log('Listening at http://localhost:2000/');
});
I want to be able to access the application from root path: http://localhost:2000 and not http://localhost:2000/dist.
One more thing, is there any way to move all the external dependancies from node_modules to dist with webpack (without the need to include the script tag in the index.html file)?
First of all for set application start point you need to set publicPath to "/" or publicPath: 'http://localhost:2000'
Your second question
Is there any way to move all the external dependancies from node_modules to dist with webpack?
Yes
You can use different file just for external modules and bundle that file. You don't need to take care of index.html file let webpack plugin HtmlWebpackPlugin take care of it.
First step set entry points for your app
entry: {
'vendors': './src/vendors.ts',//your external libraries
'app': './src/main.ts' //your app
}
and out put
output: {
publicPath: '/',
filename: '[name].js'//this will generate two different files app.js, vendor.js
}
How to add HtmlWebpackPlugin?
Add this in you plugins
new HtmlWebpackPlugin({
template: "./src/index.html",
minify:false
})
Now it will place script tags for you
on you server configuration change your public path to
publicPath: '/',

Resources