Keep getting [WDS] Disconnected! error, ReactJs, Webpack - javascript

This question relates to post: Keep getting [WDS] Disconnected! error
I have updated my webpack config settings according to the answers, however I still the "[WDS] Disconnected! error" within the console.
Please any suggestions?
webpack.config.js
var webpack = require("webpack");
var path = require("path");
module.exports = {
devtool: "inline-source-map",
entry: [
"webpack-dev-server/client?http://127.0.0.0:8080/",
"webpack/hot/only-dev-server",
"./src"
],
devServer: {
contentBase: "./public",
hot: true,
inline: true,
quiet: false,
noInfo: true,
stats: { colors: true }
},
output: {
path: path.join(__dirname, "./public"),
filename: "./assets/js/bundle.js"
},
resolve: {
modulesDirectrories: ["node_modules", "src"],
extentions: ["", ".js"]
},
module : {
loaders: [
{
test: /\.jsx?$/,
exclude: "/node_modules/",
loaders: ["react-hot-loader", "babel?presets[]=react,presets[]=es2015"]
},
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
{
test: /\.gif$/,
loader: "url-loader?mimetype=image/png"
},
{
test: /\.woff(2)?(\?v=[0-9].[0-9].[0-9])?$/,
loader: "url-loader?mimetype=application/font-woff"
},
{
test: /\.(ttf|eot|svg)(\?v=[0-9].[0-9].[0-9])?$/,
loader: "file-loader?name=[name].[ext]"
}
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify("development")
}
})
]}

Change the transportMode to ws instead of "sock-js.node":-
devServer: {
transportMode: 'ws',
injectClient: false,
}

This will be solved by Enabling Error Overlay,
overlay:true include one more property in devServer object
devServer: {
...
overlay: true,
}
click here for more info webpack-dev-server

Related

ERROR in ./src/components/navbar/HomeNav.js Module build failed - Webpack error

I have a react project that was created by CRA. Now i installed webpack because i wanted to add Jquery into config. Now I am getting this error after initializing webpack:
Could someone help me?
cli image
Webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin');
const InterpolateHtmlPlugin = require('interpolate-html-plugin');
module.exports = {
entry: "./src/index.js",
output: {
path: __dirname + "/dist",
filename: "./bundle.js",
},
mode: 'development',
devServer: {
port: 3000,
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env','#babel/react'],
plugins: ['#babel/proposal-class-properties', '#babel/plugin-proposal-object-rest-spread', '#babel/plugin-syntax-dynamic-import']
}
}
},
{ test: /\.(png|woff|woff2|eot|ttf|svg)$/, loader: 'url-loader' },
{
test: /\.css$/i,
use: ["style-loader", "css-loader"],
}
],
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
plugins: [
new HtmlWebpackPlugin({
template: "./dist/index.html",
filename: './index.html',
favicon: './dist/favicon.ico'
}),
new InterpolateHtmlPlugin({
PUBLIC_URL: 'static' // can modify `static` to another name or get it from `process`
})
],
};
.babelrc
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
please help

How can I get hot reloading (HMR) running with Webpack 5?

I am trying to get HMR running with webpack v5, but it does not work. When I modify and save a file, webpack re-compiles the project correctly, but the frontend does not update.
I read this article and followed the instructions: https://webpack.js.org/guides/hot-module-replacement/
This is my webpack config:
{
mode: 'development',
entry: {
babelpoly: 'babel-polyfill',
app: [ './src/index.js', './src/app.js' ]
},
plugins: [
BundleStatsWebpackPlugin { ... },
DefinePlugin { ... },
HtmlWebpackPlugin { ... }
],
stats: { ... },
output: {
path: '[pathTo]/dist',
filename: '[name].bundle.js',
chunkFilename: '[name].bundle.js'
},
optimization: {
splitChunks: { chunks: 'all' },
runtimeChunk: 'single',
usedExports: true,
mergeDuplicateChunks: true
},
module: {
rules: [
{
test: /\.(s[ac]ss)$/i,
include: path.resolve(ROOT, 'src'),
use: [
'style-loader', // Creates `style` nodes from JS strings
{
loader: 'css-loader', // Translates CSS into CommonJS
options: {
modules: {
mode: 'local',
localIdentName: devMode
? '[name]_[local]-[hash:base64:3]'
: '[local]-[hash:base64:5]',
},
},
},
{
loader: 'sass-loader', // compiles Sass to CSS
options: {
implementation: require('sass'),
},
},
],
},
{
test: /\.css$/,
include: [path.join(ROOT, 'node_modules')],
use: ['style-loader', 'css-loader'],
},
{
test: /\.(png|svg|jpg|gif)$/,
use: ['file-loader'],
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: ['file-loader'],
},
{
test: /\.m?jsx?$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: [
[
'#babel/preset-env',
{
useBuiltIns: 'entry',
corejs: 3,
},
],
'#babel/preset-react',
],
plugins: [['#babel/plugin-proposal-class-properties', {loose: true}]],
},
},
},
],
},
resolve: {
extensions: [ ... ],
alias: {
...
},
modules: [
...
]
},
devtool: 'inline-source-map',
devServer: {
port: 3003,
contentBase: '[pathTo]/dist',
host: '0.0.0.0',
hot: true,
compress: true,
disableHostCheck: true,
historyApiFallback: true,
overlay: { warnings: true, errors: true },
stats: { ... }
}
}
I am using:
webpack 5.7.0
webpack-cli 4.2.0
react 16.13
node 14.15.1
npm 6.14.8
I start webpack with this command: webpack serve --host 0.0.0.0 --config config/webpack.dev.js
What do I do wrong? Thanks for your help. :)
I believe it's a bug in webpack-dev-server v3 https://github.com/webpack/webpack-dev-server/issues/2758 when you're using it with webpack 5 and browserslist. You can wait for webpack-dev-server v4 https://github.com/webpack/webpack-dev-server/pull/2592#issuecomment-734400875, it will come soon, or use target: 'web' for the moment under your development mode.

My Vue build in webpack produces a huge (850kb) vendor file, how do I make it the expected 85kb?

Solved:
devtool: '#eval-source-map'
Includes a source map in the output
Original issue
As stated, the webpack build produces an enormous bundle/vendor file with Vue as my only import. I cannot see for the life of me how people get it down to 80kb.
As far as I can see, there is a vue-loader and the file gets minified, so why would it come out enormous?
var path = require('path') var webpack = require('webpack')
module.exports = { entry: './src/main.js', output: {
path: path.resolve(__dirname, './static'),
publicPath: '/static/',
filename: 'js/login-view.js' }, module: {
rules: [
{
test: /\.css$/,
use: [
'vue-style-loader',
'css-loader'
],
}, {
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
}
// other 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]',
useRelativePath: true,
publicPath: './static/images/'
}
}
] }, resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
},
extensions: ['*', '.js', '.vue', '.json'] }, devServer: {
historyApiFallback: true,
noInfo: true,
overlay: true }, performance: {
hints: false }, 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: false,
// compress: true,
compress: {
warnings: false
},
mangle: true,
}),
new webpack.LoaderOptionsPlugin({
minimize: true
}) ]) }
devtool: '#eval-source-map'
was the culprit. It was getting included in all builds and it puts the sourcemap in the files. I removed this and dropped the file to ~90kb.

Unexpected character '#' You may need an appropriate loader to handle this file type

This is what I get when I try to run webpack: the error I get is:
"ERROR in ./v3/app/styles/main.scss
Module parse failed: /Users/vovina/widget-login-react/v3/app/styles/main.scss Unexpected character '#' (1:0)
You may need an appropriate loader to handle this file type."
it can't resolve #import, any ideas on this?
my webpack config is as follow:
const childProcess = require('child_process')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const trimEnd = require('lodash/trimEnd')
const webpack = require('webpack')
const path = require('path')
const ENV = {
NODE_ENV: process.env.NODE_ENV,
API: 'https://accounts' + (process.env.NODE_ENV === 'prd' ? '' : '-'
+ process.env.NODE_ENV),
BUILD_VERSION: trimEnd(childProcess.execSync('git rev-list HEAD --
count').toString(), '\n'),
BUILD_DATE: trimEnd(childProcess.execSync('git log --format="%cd" -n
1').toString(), '\n'),
BUILD_COMMIT_ID: trimEnd(childProcess.execSync('git log --format="%h"
-n 1').toString(), '\n')
}
const prodLikeEnvironment = process.env.NODE_ENV === 'stg' ||
process.env.NODE_ENV === 'prd'
const CSS_MAPS = !prodLikeEnvironment
module.exports = {
entry: {
init: [
'./app/init.js'
],
login: [
'./app/login.js'
],
authentication: [
'./v3/app/authenticator.js'
],
common: [
'./app/common.js'
]
},
target: 'web',
output: {
path: path.join(__dirname, 'dist', process.env.NODE_ENV),
pathinfo: true,
publicPath: '/assets/widgets/login/v2/',
filename: '[name].bundle.js',
chunkFilename: '[id].bundle.js',
libraryTarget: 'umd'
},
resolve: {
alias: {
'react': 'preact-compat',
'react-dom': 'preact-compat'
},
modules: [
path.resolve('./app'),
path.resolve('./node_modules')
]
},
module: {
loaders: [
{
test: /\.jsx?$/,
loaders: ['babel-loader'],
exclude: [/bower_components/, /node_modules/]
},
{
// Transform our own .(scss|css) files with PostCSS and CSS-modules
test: /\.(scss|css)$/,
include: [path.resolve(__dirname, 'v3/app')],
options: {
sourceMap: true
},
loader: [
`style-loader?singleton`,
`css-loader?modules&importLoaders=1&localIdentName=
[local]${process.env.CSS_MODULES_IDENT ||
'_[hash:base64:5]'}&sourceMap=${CSS_MAPS}`,
'postcss-loader',
`sass-loader?sourceMap=${CSS_MAPS}`
].join('!')
},
{
test: /\.(scss|css)$/,
exclude: [path.resolve(__dirname, 'v3/app')],
options: {
sourceMap: true
},
loader: [
`style-loader?singleton`,
`css-loader?sourceMap=${CSS_MAPS}`,
`postcss-loader`,
`sass-loader?sourceMap=${CSS_MAPS}`
].join('!')
},
{
test: /\.(svg|eot|woff|woff2?|ttf|otf)$/,
use: 'base64-font-loader'
},
{
test: /.json$/,
loader: 'json'
},
{
test: /\.jpe?g$|\.gif$|\.png$/,
use: 'base64-image-loader'
},
{
test: /\.html?$/,
loader: 'html'
},
{
test: /\.js$/,
loader: 'strip-loader?strip[]=debug,strip[]=console.log,strip[]=console.debug,strip[]=console.info'
}
]
},
plugins: [
new webpack.LoaderOptionsPlugin({
minimize: true
// postcss: [
// autoprefixer({ browsers: 'last 2 versions' })
// ]
}),
new CopyWebpackPlugin([
{ from: 'public' }
]),
new ExtractTextPlugin('[name].bundle.css'),
new webpack.DefinePlugin({
ENV: JSON.stringify(ENV),
// Only used for react prod bundle. Refer to ENV.NODE_ENV for business
logic
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new webpack.NoEmitOnErrorsPlugin(),
new webpack.optimize.UglifyJsPlugin({
output: {
comments: false
},
compress: {
unsafe_comps: true,
properties: true,
keep_fargs: false,
pure_getters: true,
collapse_vars: true,
unsafe: true,
warnings: false,
screw_ie8: true,
sequences: true,
dead_code: true,
drop_debugger: true,
comparisons: true,
conditionals: true,
evaluate: true,
booleans: true,
loops: true,
unused: true,
hoist_funs: true,
if_return: true,
join_vars: true,
cascade: true,
drop_console: true
}
})
]
}
You are using the (scss|css) twice in your configuration file.
Remove that and use the code posted blow:
Before using, you must first npm install raw-loader.
I think you've already installed the sass-loader.
{
test: /\.css$/,
include: helpers.root('src', 'app'),
loader: 'raw-loader'
},
// // css global which not include in components
{
test: /\.css$/,
exclude: helpers.root('src', 'app'),
use: ExtractTextPlugin.extract({
use: 'raw-loader'
})
},
{
test: /\.scss$/,
include: helpers.root('src', 'app'),
use: ['raw-loader', 'sass-loader']
},
// // SASS global which not include in components
{
test: /\.scss$/,
exclude: helpers.root('src', 'app'),
use: ExtractTextPlugin.extract({
use: ['raw-loader', 'sass-loader']
})
}
Add my root()function.
var path = require('path');
var _root = path.resolve(__dirname, '..');
function root(args) {
args = Array.prototype.slice.call(arguments, 0);
return path.join.apply(path, [_root].concat(args));
}
exports.root = root;
Hope this will work.

webpack dev server does not show the content

I have the following problem when running the webpack dev server:
when I run npm start, it show the following:
➜ directory git:(staging) ✗ npm start
directory #1.0.0 start directory
BUILD_DEV=1 BUILD_STAGING=1 ./node_modules/webpack-dev-server/bin/webpack-dev-server.js
http://localhost:8080/
webpack result is served from /undefined/
content is served from
directory
404s will fallback to /index.html
Hash: 75773622412153d5f921
Version: webpack 1.12.11
Time: 43330ms
I guess the problem might because the following line:
webpack result is served from /undefined/
When I open the browser at http://localhost:8080/, it appear as follow:
Cannot GET /
and there is no thing in the console.
Do you have any ideas for this problem ?
UPDATE: WEBPACK CONFIG FILE
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const merge = require('webpack-merge');
const nodeModulesDir = path.resolve(__dirname, 'node_modules');
const deps = [
'moment/min/moment.min.js',
'underscore/underscore-min.js',
];
/* Include SASS path here if you want to this in your sass files:
* #import 'bourbon';
*/
const bourbon = require('node-bourbon').includePaths;
const TARGET = process.env.npm_lifecycle_event;
const ROOT_PATH = path.resolve(__dirname);
const SASS_DEPS = [bourbon].toString();
const BUILD_NUMBER = process.env.CI_BUILD_NUMBER;
const common = {
entry: path.resolve(ROOT_PATH, 'app/index.js'),
output: {
filename: BUILD_NUMBER + '-[hash].js',
path: path.resolve(ROOT_PATH, 'build'),
publicPath: `/${BUILD_NUMBER}/`,
},
module: {
loaders: [
{
test: /\.scss$/,
loaders: ['style', 'css', 'sass?includePaths[]=' + SASS_DEPS],
include: path.resolve(ROOT_PATH, 'app'),
},
{
test: /\.css$/,
loaders: [
'style',
'css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]',
'sass?includePaths[]=' + SASS_DEPS,
'postcss'
],
include: path.resolve(ROOT_PATH),
exclude: /(pure\/grids|Grids).*\.css$/,
},
{
test: /(pure\/grids|Grids).*\.css$/,
loaders: [
'style',
'css',
'sass?includePaths[]=' + SASS_DEPS,
],
include: path.resolve(ROOT_PATH),
},
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url-loader?limit=10000&minetype=application/font-woff',
},
{ test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'file-loader',
},
{
test: /\.json$/,
loader: 'json',
},
],
},
plugins: [
new HtmlWebpackPlugin({
title: 'My App',
template: path.resolve(ROOT_PATH, 'app/index.html'),
inject: 'body',
minify: {
removeComments: true,
collapseWhitespace: true,
},
}),
new webpack.DefinePlugin({
__DEV__: JSON.stringify(JSON.parse(process.env.BUILD_DEV || 'false')),
__STAGING__: JSON.stringify(JSON.parse(process.env.BUILD_STAGING || 'false')),
__API_HOST__: JSON.stringify(process.env.BUILD_STAGING ? 'my.api' : 'my.api'),
}),
],
resolve: {
alias: {
'styles': path.resolve(ROOT_PATH, 'app/styles'),
},
extensions: ['', '.js', '.jsx', '.json'],
},
postcss: function() {
return [
require('postcss-import'),
require('autoprefixer'),
require('postcss-cssnext'),
]
}
};
if (TARGET === 'start' || !TARGET) {
module.exports = merge(common, {
output: {
filename: '[hash].js',
path: path.resolve(ROOT_PATH, 'build'),
publicPath: '/',
},
devtool: 'eval-source-map',
module: {
loaders: [
{
test: /\.jsx?$/,
loaders: [
'react-hot',
'babel-loader'
],
include: path.resolve(ROOT_PATH, 'app'),
},
],
},
devServer: {
colors: true,
historyApiFallback: true,
hot: true,
inline: true,
progress: true,
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
],
});
} else if (TARGET === 'build' || TARGET === 'builds') {
const config = {
resolve: {
alias: {},
},
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel-loader',
include: path.resolve(ROOT_PATH, 'app'),
},
],
noParse: [],
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
minimize: true,
compressor: {
screw_ie8: true,
warnings: false,
},
compress: {
warnings: false,
},
output: {
comments: false,
},
}),
new webpack.optimize.DedupePlugin(),
new webpack.DefinePlugin({
'process.env': { 'NODE_ENV': JSON.stringify(process.env.NODE_ENV) },
}),
],
};
deps.forEach((dep) => {
const depPath = path.resolve(nodeModulesDir, dep);
config.resolve.alias[dep.split(path.sep)[0]] = depPath;
config.module.noParse.push(depPath);
});
module.exports = merge(common, config);
}
Same problem occurred to me when i started using babel-loader > 6.
It was fixed by adding contentBase in webpack dev server configuration.
In my case it looked like this
new WebPackDevServer(webpack(config), {
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: true,
contentBase: __dirname + '/public'
}).listen(3000, 'localhost')
I would be great to see your webpack config file to pin point the exact problem, but from the error message, there could be multiple problem
Make sure you are on the right port
Make sure your webpack config has
path and public path setup
Make sure you have contentBase setup as
well
Without seeing your webpack file and more concrete detail, it is quite hard to pinpoint the issue. But you can always go to https://webpack.github.io/docs/webpack-dev-server.html for information on how to set it up.

Categories

Resources