Webpack 5 livereload enabled but not working - docker

I'm having trouble with the Live Reload in Webpack 5 not working. The browser console says:
[webpack-dev-server] Live Reloading enabled.
but it does not reload when I change/save a file. There are no errors in the browser console or terminal.
I'm on Windows 10, using an official Alpine Linux Docker image; my browser is Chrome Version 102.0.5005.63 (Official Build) (64-bit). The project is a fairly simple front end web app.
My package.json dev dependencies:
"devDependencies": {
"html-webpack-plugin": "^5.5.0",
"webpack": "^5.72.0",
"webpack-cli": "^4.9.2",
"webpack-dev-server": "^4.9.0",
"webpack-webmanifest-loader": "^2.0.2" }
My webpack.config.js file:
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: "./src/index.js",
mode: "development",
devtool: "inline-source-map",
target: "web",
devServer: {
static: {
directory: path.join(__dirname, "src"),
},
compress: true,
hot: false,
port: 3000,
liveReload: true,
watchFiles: "./src/*",
},
plugins: [
new HtmlWebpackPlugin({
title: "Title",
template: "src/index.html",
}),
],
output: {
filename: "[name].bundle.js",
path: path.resolve(__dirname, "dist"),
clean: true,
},
module: {
rules: [
{
test: /\.(png|svg|webp|jpg|jpeg)$/i,
type: "asset/resource",
},
{
test: /\.(json|txt|mp3)$/i,
type: "asset/resource",
},
{
test: /\.webmanifest$/i,
use: "webpack-webmanifest-loader",
type: "asset/resource",
},
],
},
};
When starting the dev server I use the following commands:
npx webpack serve --static assets
My file/folder structure:
New to Webpack in general. Please help!

After sifting through lots of google searches, I finally found a solution in the official webpack documentation: watchOptions.
If watching does not work for you, try out this option. This may help issues with NFS and machines in VirtualBox, WSL, Containers, or Docker. In those cases, use a polling interval and ignore large folders like /node_modules/ to keep CPU usage minimal.
Sooo.... still not sure why it doesn't work with the regular watch option, but polling does work at this time in a docker container.
Here's my webpack.config.js file:
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: "./src/index.js",
mode: "development",
devtool: "inline-source-map",
target: "web",
devServer: {
static: ["assets"],
compress: true,
hot: false,
port: 3000,
},
watchOptions: {
ignored: "/node_modules/",
poll: 1000, // Check for changes every second
},
output: {
filename: "[name].bundle.js",
path: path.resolve(__dirname, "dist"),
clean: true,
},
plugins: [
new HtmlWebpackPlugin({
title: "Title",
template: "src/index.html",
}),
],
module: {
rules: [
{
test: /\.(png|svg|webp|jpg|jpeg|json|txt|mp3)$/i,
type: "asset/resource",
},
{
test: /\.webmanifest$/i,
use: "webpack-webmanifest-loader",
type: "asset/resource",
},
],
},
};
I use the following command to start it:
npx webpack serve

Related

cypress 12 docker throw error socket_posix.cc(93)] CreatePlatformSocket() failed: Address family not supported by protocol (97)

I upgraded my cypress version from cypress 8 to cypress 12.
I am executing all my test cases on jenkins server OS centos 7 using base image cypress/base:16.13.0.
When I executed all the test cases on my local window 10 using same docker image cypress/base:16.13.0 and "cypress": "^12.3.0",All works perfectly good.
BUT when I trying to run the same project on Jenkins server centos 7 OS, throw an error
[476:0123/104731.525262:ERROR:socket_posix.cc(93)] CreatePlatformSocket() failed: Address family not supported by protocol (97)
Note : When I executed the same package (test cases) on cypress 8 all works good.
Kindly suggest me how to fix this?
cypress.config.js file :
const { defineConfig } = require('cypress');
const createBundler = require('#bahmutov/cypress-esbuild-preprocessor');
const addCucumberPreprocessorPlugin =
require('#badeball/cypress-cucumber-preprocessor').addCucumberPreprocessorPlugin;
const createEsbuildPlugin =
require('#badeball/cypress-cucumber-preprocessor/esbuild').createEsbuildPlugin;
module.exports = defineConfig({
defaultCommandTimeout: 5000,
numTestsKeptInMemory: 0,
viewportWidth: 1360,
viewportHeight: 768,
env: {
username: 'xxxx',
password: '',
},
"retries": 1,
"video": false,
e2e: {
// Integrate #bahmutov/cypress-esbuild-preprocessor plugin.
async setupNodeEvents(on, config) {
const bundler = createBundler({
plugins: [createEsbuildPlugin(config)],
});
// This is required for the preprocessor to be able to generate JSON reports after each run, and more,
on('file:preprocessor', bundler);
await addCucumberPreprocessorPlugin(on, config);
return config;
},
specPattern: 'cypress/e2e/**/*.feature',
},
});
Package.json
"#badeball/cypress-cucumber-preprocessor": "^15.1.0",
"#deepakvishwakarma/cucumber-json-formatter": "^0.0.3",
"cypress": "^12.3.0",
"moment": "^2.29.4",
"multiple-cucumber-html-reporter": "^3.1.0"
},
"dependencies": {
"#bahmutov/cypress-esbuild-preprocessor": "^2.1.5",
"cypress-xpath": "^2.0.1"
},
"cypress-cucumber-preprocessor": {
"stepDefinitions": "cypress/e2e/**/*.cy.js",
"commonPath": "cypress/e2e/common/**/*.cy.js",
"filterSpecs": true,
"omitFiltered": true,
"nonGlobalStepDefinitions": true,
"json": {
"enabled": true,
"output": "cypress/cucumber_report/log.json",
"formatter": "node",
"args": [
"./node_modules/#deepakvishwakarma/cucumber-json-formatter/lib/main.js"
]
},
"cucumberJson": {
"generate": true,
"outputFolder": "cypress/cucumber_report",
"filePrefix": "",
"fileSuffix": ".cucumber"
}
}
}

Vue CLI HMR not working after upgrading to v5

I'm developing a Django+Vue app using VSCode devcontainers (Docker).
I have recently migrated from Vue CLI v4 to Vue CLI v5 following the migration guide.
After the migration, the HMR of the dev-server stopped working.
This was my vue.config.js before the migration:
const BundleTracker = require("webpack-bundle-tracker");
module.exports = {
publicPath: process.env.NODE_ENV === "development" ? "http://localhost:8080/" : "/static/",
devServer: {
host: "0.0.0.0",
port: 8080,
public: "0.0.0.0:8080",
https: false,
headers: { "Access-Control-Allow-Origin": ["*"] },
hotOnly: true,
watchOptions: {
ignored: "./node_modules/",
aggregateTimeout: 300,
poll: 1000,
},
},
transpileDependencies: ["vuetify"],
css: {
sourceMap: true,
},
chainWebpack: (config) => {
config.plugin("BundleTracker").use(BundleTracker, [
{
filename: `./config/webpack-stats-${process.env.NODE_ENV}.json`,
},
]);
config.resolve.alias.set("__STATIC__", "static");
},
};
And after:
const { defineConfig } = require("#vue/cli-service");
const BundleTracker = require("webpack-bundle-tracker");
module.exports = defineConfig({
publicPath: process.env.NODE_ENV === "development" ? "http://localhost:8080/" : "/static/",
devServer: {
host: "0.0.0.0",
port: 8080,
client: {
webSocketURL: "auto://0.0.0.0:8080/ws",
},
https: false,
headers: { "Access-Control-Allow-Origin": ["*"] },
hot: "only",
static: {
watch: {
ignored: "./node_modules/",
aggregateTimeout: 300,
poll: 1000,
},
},
},
transpileDependencies: ["vuetify"],
css: {
sourceMap: true,
},
chainWebpack: (config) => {
config.plugin("BundleTracker").use(BundleTracker, [
{
filename: `./config/webpack-stats-${process.env.NODE_ENV}.json`,
},
]);
config.resolve.alias.set("__STATIC__", "static");
},
});
After the migration, a new warning shows everytime I run npm run serve (but devServer.public has been removed in v5!):
App running at:
- Local: http://localhost:8080/
It seems you are running Vue CLI inside a container.
Since you are using a non-root publicPath, the hot-reload socket
will not be able to infer the correct URL to connect. You should
explicitly specify the URL via devServer.public.
Access the dev server via http://localhost:<your container's external mapped port>http://localhost:8080/
Note that the development build is not optimized.
To create a production build, run npm run build.
Any ideas?
Thanks in advance!
My team had similar issues as you are describing. We could fix it by adding the optimization object to our Webpack config (vue.config.js`).
const {defineConfig} = require('#vue/cli-service');
module.exports = defineConfig({
/* your config */
configureWebpack: {
optimization: {
runtimeChunk: 'single',
},
},
devServer: {
// we need this for apollo to work properly
proxy: `https://${process.env.SANDBOX_HOSTNAME}/`,
host: '0.0.0.0',
allowedHosts: 'all',
},
});
The optimization part fixed the HMR for us. However, if you're using Firefox, your console might still be spammed by error messages like these:
The connection to wss://SANDBOX_HOSTNAME:8080/ws was interrupted while
the page was loading.
This has been a blocker of vue 3 for us, so I hope it helps. ✌️

Vue cli. How to build with the same hash

i have a problem with hashes in vue cli build.
And now to the details.
I build my app, and in dist folder i see my files with names like
app.dsadas.js, chunk-1-dsadaas.js etc.. all looks good.
But i build my app in docker images, there may be 2 or more, and i need all this images with the same hashes in filenames, but it is not.
This 'webpack-md5-hash' plugin helped me with this problem, but its very old solution, works with warnings.
Help pls find solution for webpack 4.
This is my vue config file:
const path = require('path');
const VuetifyLoaderPlugin = require('vuetify-loader/lib/plugin');
const CompressionWebpackPlugin = require('compression-webpack-plugin');
const productionGzipExtensions = ['js', 'css'];
function resolve(dir) {
return path.resolve(__dirname, dir);
}
module.exports = {
assetsDir: 'static',
runtimeCompiler: true,
lintOnSave: process.env.NODE_ENV !== 'production',
devServer: {
overlay: {
warnings: true,
errors: true,
},
},
configureWebpack: {
performance: {
hints: false,
},
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
vue$: 'vue/dist/vue.esm.js',
'#': resolve('src'),
utils: resolve('src/utils'),
api: resolve('src/api'),
defaultStates: resolve('src/store/modules/defaultStates'),
router: resolve('src/router'),
store: resolve('src/store'),
config: resolve('src/config'),
helpers: resolve('src/store/modules/helpers'),
constants: resolve('src/constants'),
mixins: resolve('src/mixins'),
},
},
plugins: [
new VuetifyLoaderPlugin(),
new CompressionWebpackPlugin({
filename: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp(`\\.(${productionGzipExtensions.join('|')})$`),
threshold: 10240,
minRatio: 0.8,
}),
],
},
};

Browser doesn't pickup local file change when running webpack watch

I try to run our ASP.NET MVC project with webpack2. As the first step, I set up webpack2 with ExtractTextPlugin.
When running webpack watch, I can see that the bundled css file gets updated.
But if I run the project with IISExpress and with webpack watch running, the browser just won't pickup the latest change even though the file has changed.
Verified that if I turn off webpack watch and refresh the browser, then I can see those changes in the browser.
I am running without webpack dev server, here is the webpack.config.js:
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const path = require('path');
module.exports = env => {
return {
entry: {
"main": "./static/entry.js",
"component": path.resolve(__dirname, "../component/static/bundle.js")
},
output: {
path: path.resolve(__dirname, "./static/dist/scripts"),
filename: "[name].index.js"
},
module: {
rules: [
{
test: /\.scss$/,
exclude: /node_modules/,
use:ExtractTextPlugin.extract({
fallback: "style-loader",
use: [
{
loader: 'css-loader',
},
{
loader: 'sass-loader',
options: {
sourceMap: true,
includePaths: [
path.resolve(__dirname, './default.css'),
path.resolve(__dirname, './normalize.css')
]
}
}
]
})
},
{ test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ },
{ test: /\.ts$/, loader: 'babel-loader', exclude: /node_modules/ }
]
},
plugins: [
new webpack.ProvidePlugin({
$: path.resolve(__dirname, './node_modules/jquery/src/jquery'),
jQuery: path.resolve(__dirname, './node_modules/jquery/src/jquery'),
moment: path.resolve(__dirname, './node_modules/moment/moment')
}),
new ExtractTextPlugin({
filename: "../style/[name].style.css",
allChunks: true
}),
new webpack.optimize.UglifyJsPlugin({
minimize: true,
compress: {
warnings: false
}
})
]
}
};
The issue is constant and I have no idea what could have happened, help please.
I found the cause of this problem.
Project web.config is caching the client resources, disable output caching fixed the issue.
<caching>
<outputCache enableOutputCache="false" />
</caching>

ng-bootstrap AoT build failure with Unexpected Token and missing loader

I am trying to use ng-bootstrap library in my project. Runs fine with webpackdevserver and jit build but aot build throw errors similar to following
Module parse failed: E:\SVNCode\Learning\spa\aot\node_modules\#ng-
bootstrap\ng-bootstrap\alert\alert.ngfactory.ts Unexpected token (13:21)
You may need an appropriate loader to handle this file type.
I have searched for the issue but the only reference related to ng-bootstrap was ticket no. #1381 on github, which was closed without any further details. So, I believe that I may be missing something very small. Here are relevant details
Node : 8.1.3
Angular & Compiler-cli: 4.2.4
Webpack : 2.6.1
typescript : 2.3.4
ng-bootstrap : 1.0.0-alpha.26
bootstrap : 4.0.0-alpha.6 (using CDN but tried after install also with
same result)
webpack.prod.js
let ExtractTextPlugin = require('extract-text-webpack-plugin');
let webpack = require('webpack');
let HtmlWebpackPlugin = require('html-webpack-plugin');
let CompressionPlugin = require("compression-webpack-plugin");
let CopyWebpackPlugin = require('copy-webpack-plugin');
let path = require('path');
let rootDir = path.resolve(__dirname, '..');
module.exports = {
entry: {
'polyfills': './spa/polyfills.ts',
'vendor': './spa/vendor-aot.ts',
'app': './spa/main-aot.ts' // AoT compilation
},
output: {
path: path.join(rootDir,'wwwroot'),
filename: 'js/[name]-[hash:6].bundle.js',
chunkFilename: 'js/[id]-[hash:6].chunk.js',
publicPath: '/'
},
resolve: {
extensions: ['.ts', '.js', '.json', '.css', '.html']
},
module: {
rules: [
{
test: /\.ts$/,
use: [
'babel-loader?presets[]=es2015',
'awesome-typescript-loader?configFileName=tsconfig-aot.json',
'angular-router-loader?aot=true&genDir=spa/aot/'
],
exclude: /node_modules/
},
{
test: /\.css$/,
loaders: ['to-string-loader', 'css-loader']
},
{
test: /\.html$/,
use: 'html-loader'
}
],
exprContextCritical: false
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: ['app', 'vendor', 'polyfills']
}),
new webpack.LoaderOptionsPlugin({
minimize: true,
debug: false
}),
new webpack.optimize.UglifyJsPlugin({
beautify: false,
compress: {
warnings: false
},
output: {
comments: false
},
sourceMap: false,
mangle: {keep_fnames: true}
}),
new CompressionPlugin({
asset: "[path].gz[query]",
algorithm: "gzip",
test: /\.js$|\.html$/,
threshold: 10240,
minRatio: 0.8
}),
new ExtractTextPlugin("[name].css"),
new HtmlWebpackPlugin({
template: './spa/index.html'
}),
new CopyWebpackPlugin([
{ from: path.join(rootDir,'spa','assets'), to: 'assets'}
]),
new webpack.NoEmitOnErrorsPlugin()
]
};
tsconfig-aot.js
{
"compilerOptions": {
"target": "es2015",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": true,
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true,
"lib": ["es2015","dom"],
"typeRoots": ["node_modules/#types"],
"types":["node", "core-js"]
},
"files": [
"spa/app/app.module.ts",
"spa/main-aot.ts"
],
"exclude": ["node_modules"],
"angularCompilerOptions": {
"genDir": "spa/aot",
"skipMetadataEmit": true
},
"awesomeTypescriptLoaderOptions":{
"useWebpackText": true,
"useCache": true
}
}
vendor-aot.ts
import '#angular/platform-browser';
import '#angular/core';
import '#angular/common';
import '#angular/http';
import '#angular/forms';
import '#angular/router';
import '#angular/platform-browser/animations';
import 'rxjs';
//can import others e.g. bootstrap, jquery etc
//can import js, ts, css, sass etc..
import '#ng-bootstrap/ng-bootstrap';
Thanks & Regards
After searching the internet high and low, going through several stackoverflow posts and github project configurations/samples, I finally managed to fix it (duct tape way).
All I had to do to fix the issue was remove the exclusion of node_modules folder in webpack config file.
Now, WHY exclusion of node_modules works for angular and rxjs packages but not for ng-bootstrap, is still beyond me.
Exclusion works when building for jit but for aot to succeed node_modules HAS TO BE INCLUDED in ts loader chain. Now the build time for aot has increased multifold, but at least it works.

Resources