Vue CLI HMR not working after upgrading to v5 - docker

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. ✌️

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"
}
}
}

Webpack 5 livereload enabled but not working

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

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,
}),
],
},
};

Does anybody know how to proxy the index.html in webpack-dev-server or similar?

I have MVC as my backend. MVC controllers/views have _StartPage.cshtml, _Layout.cshtml (They are combined to form _index.cshtml).
So, I need to use webpack dev server proxy to fetch the index.html from backeend server. Is there any way to do it?
So far this is what I've come up with
devServer: {
historyApiFallback: true,
index: '',
contentBase: "./",
port: 8000,
proxy: [{
//Only works for api, index.html does not
context: ['/index.html', '/api'],
target: 'http://localhost',
pathRewrite: { '^/api': '/TestApp/api' }
}]
},
I'm open to use any other client server beside webpack-dev-server if that solves the problem?
Please note that this will be used only in Development Not in production.
I think you want a different entry for each path. Something like this maybe?
devServer: {
contentBase: './',
port: 8000
proxy: {
'/index.html': {
target: 'http://localhost/',
pathRewrite: { '^/': 'TestApp/index.html' },
},
'/api': {
target: 'http://localhost/',
pathRewrite: { '^/api': '/TestApp/api' }
},
},
}
How about your project structure?
The webpack-dev-server must be used in development mode, after build and deployed, you need to change the api url for production mode.
I'm a front-end and I meet similar problem, I solve it by DefinePlugin that could change api in different mode.
My webpack like this:
├webpack.common.js
├webpack.dev.js
├webpack.prod.js
webpack.common.js
devServer: {
// contentBase: 'dist/',
historyApiFallback: true,
watchOptions: { aggregateTimeout: 300, poll: 1000 },
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
"Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization"
},
proxy: {
'/': {
target: 'xxxxxxxxxxxx/website/',//url
changeOrigin: true,
secure: false,
}
}
},
webpack.dev.js
plugins:[
new webpack.DefinePlugin({
'SERVICE_URL': JSON.stringify('')
})
]
webpack.prod.js
plugins:[
new webpack.DefinePlugin({
'SERVICE_URL': JSON.stringify('https://xxx.api.com/') //real api
})
]
fetch/ajax code
console.log(SERVICE_URL)
$.ajax({
url: SERVICE_URL+'api/%E6%AD%A6%E6%BC%A2%E8%82%BA%E7%82%8E_%E5%8F%B0%E5%95%86_simple.json',
...
This is my solution, I hope it could give some inspiration.

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>

Resources