HotModuleReplacement not connecting - asp.net-core

I am currently trying to use webpack for the first time in a project and have set up a ASP.NET Core project with the following in the Startup.cs file
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
{
HotModuleReplacement = true
});
I have Styles folder which contains some .less files too and I have a webpack.config.js in the root of the project, containing:
const path = require("path");
const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = (env) => {
return [{
mode: 'development', //TODO Make configurable
entry: { 'main': './app.js' },
output: {
path: path.resolve(__dirname, "wwwroot"),
filename: "js/[name].js",
publicPath: "/"
},
plugins: [
new MiniCssExtractPlugin({
filename: 'css/[name].css'
})
],
module: {
rules: [
{
test: /\.(less)$/,
include: [
path.resolve(__dirname, "Styles")
],
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'less-loader'
]
}
]
}
}];
}
When I run my application, I can see in the output that it is compiling the webpack bundles and I see my files in the js and css folder of wwwroot, which suggests it is finding the webpack config file, I also see lines like below which suggests it is attempting something with the webpack-hot-middleware plugin:
[./node_modules/html-entities/index.js] 231 bytes {main} [built]
[./node_modules/querystring-es3/decode.js] 2.45 KiB {main} [built]
[./node_modules/querystring-es3/encode.js] 2.48 KiB {main} [built]
[./node_modules/querystring-es3/index.js] 127 bytes {main} [built]
[./node_modules/webpack-hot-middleware/client-overlay.js] (webpack)-hot-middleware/client-overlay.js 2.17 KiB {main} [built]
[./node_modules/webpack-hot-middleware/client.js?path=__webpack_hmr&dynamicPublicPath=true] (webpack)-hot-middleware/client.js?path=__webpack_hmr&dynamicPublicPath=true 7.68 KiB {main} [built]
but then I don't see any other reference to HMR, and I don't get the [HMR] connected line in the console to signify it has linked up.
Is there anything I am missing in this setup?

I found the problem.....I was being stupid and had forgotten to actually include the is file that is output by webpack, because all I was using for at that point was to compile my less files into CSS!

Related

how to use react-monaco-editor together with worker-loader?

Describe the bug
react-monaco-editor cannot be used together with worker-loader.
To Reproduce
create a new typescript app with CRA, run a min react-monaco-editor demo. (everything is fine)
install worker loader and add config in config-overrides.js, and start app.
example repo to reproduce
ERROR in ./node_modules/monaco-editor/esm/vs/editor/editor.worker.js
Module build failed (from ./node_modules/worker-loader/dist/cjs.js):
TypeError: Cannot read properties of undefined (reading 'replace')
at getDefaultChunkFilename (/Users//Documents/test/my-project/node_modules/worker-loader/dist/utils.js:23:24)
at Object.pitch (/Users//Documents/test/my-project/node_modules/worker-loader/dist/index.js:61:108)
Child vs/editor/editor compiled with 1 error
assets by status 1.27 KiB [cached] 1 asset
./node_modules/monaco-editor/esm/vs/language/json/json.worker.js 39 bytes [not cacheable] [built] [1 error]
ERROR in ./node_modules/monaco-editor/esm/vs/language/json/json.worker.js
Module build failed (from ./node_modules/worker-loader/dist/cjs.js):
TypeError: Cannot read properties of undefined (reading 'replace')
at getDefaultChunkFilename (/Users//Documents/test/my-project/node_modules/worker-loader/dist/utils.js:23:24)
at Object.pitch (/Users//Documents/test/my-project/node_modules/worker-loader/dist/index.js:61:108)
Child vs/language/json/jsonWorker compiled with 1 error
details of my config-overrides.js
const webpack = require('webpack');
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');
module.exports = function override(config, env) {
config.plugins.push(
new MonacoWebpackPlugin({
languages: ['json']
})
);
config.stats = {
children: true
}
config.module.rules.push(
{
test: /\.worker\.js$/,
use: {
loader: 'worker-loader',
options: {
inline: 'fallback',
filename: '[contenthash].worker.js',
},
},
},
{
test: /\.worker\.ts$/,
use: [
{
loader: 'worker-loader',
options: {
inline: 'fallback',
filename: '[contenthash].worker.js',
},
},
'ts-loader',
],
},
);
return config;
};
Environment (please complete the following information):
OS: MacOS
Browser Chrome
Bundler webpack5 (CRA)
[ ] I will try to send a pull request to fix this issue.
I have solved it. It seems not to be a problem of react-monaco-editor or monaco-editor.
The problem is between worker-loader and monaco-editor-webpack-plugin.
I temporarily update my worker-loader config to match workers in my src folder only and solve this problem.
It could be better to figure out how to configure it in monaco-editor-webpack-plugin because it build files contains worker from monaco-editor without hashcode.

Workbox webpack plugin is not loading assets (.js) from cache after installed

I am trying to set up a PWA for an app in Laravel (5.8) with vuejs (2.5).
This is the configuration I have in mix.js:
...
mix.js('resources/js/app.js', 'public/js')
.generateSW({
// Define runtime caching rules.
runtimeCaching: [{
// Match any request that ends with .png, .jpg, .jpeg or .svg.
urlPattern: /\.(?:png|jpg|jpeg|svg)$/,
// Apply a cache-first strategy.
handler: 'CacheFirst',
options: {
// Use a custom cache name.
cacheName: 'images',
// Only cache 10 images.
expiration: {
maxEntries: 10,
},
},
}],
skipWaiting: true
})
.vue()
.copy('node_modules/lodash/lodash.min.js', 'public/js')
.copy('./resources/manifest.json', 'public/dist/manifest.json')
.copy('./resources/icons', 'public/dist/')
.extract(['vue'])
.webpackConfig({
output: {
filename: '[name].js',
chunkFilename: `[name].chunk.[contenthash:8].js`,
path: path.join(__dirname, 'public/dist'),
publicPath: '/dist/'
},
resolve: {
alias: {
'vue$': 'vue/dist/vue.common.js',
'variables': path.resolve('resources/sass/_variables.scss')
}
},
plugins: [
new webpack.ContextReplacementPlugin(
/moment[\/\\]locale$/,
/(en|es)$/
),
]
})
.options({
processCssUrls: false,
});
...
The service worker was installed correctly and the first time it loads it caches my assets.
But the next calls I make (reload the page) don't use that cache and reload the assets from the network.
However, what I am looking for is a quick initial load after the PWA is installed and this is not happening.
I have done this before with Angular and the PWA module and the assets are loaded from cache, and if there are changes, they are updated later, which makes the initial load of the application very fast.
Can someone help me with this?
In the end I ended up using workbox-cli with this setup:
// workbox.config.js
module.exports = {
"globDirectory": "public/",
"globPatterns": [
"**/*.{js,css,ico,woff2,webmanifest}",
"**/images/icons/*",
"**/images/*",
],
// 15mb max file size
maximumFileSizeToCacheInBytes: 15 * 1024 * 1024,
globIgnores: [
'**/mix-manifest.json',
'**/js/{manifest,vendor}.js',
'**/js/chunks/*',
],
"swDest": "public/service-worker.js",
"swSrc": "resources/sw-offline.js"
};
And running this at the end of my npm run prod
workbox injectManifest workbox.config.js
All credit to this repository:
https://github.com/aleksandertabor/flashcards

Force change vue js/css assets hash (fingerprint)

Building vue app in production as in:
NODE_ENV=production vue-cli-service build
Adds the static assets hash fingerprints as below:
dist/js/chunk-vendors.d710a916.js 986.81 KiB 297.69 KiB
dist/js/app.ad3f94f2.js 231.00 KiB 56.02 KiB
dist/3115008e.worker.js 30.59 KiB 9.98 KiB
dist/css/app.7eecdb26.css 174.87 KiB 24.16 KiB
dist/css/chunk-vendors.565b13d4.css 42.77 KiB 6.81 KiB
The assets are served with a high maxage cache. Due to some issues involving the headers of these static assets, I want to force renaming all assets, preferably via changing the length of the hash fingerprint (or the algorithm).
So in vue.config.js I added:
module.exports = {
configureWebpack: {
output: {
hashFunction: 'sha256',
hashDigestLength: 8,
},
...
}
The problem is that it affects only dist/3115008e.worker.js (the hash changes, and length increases to 8). All other assets name remain unchanged.
What changes are required to modify the hash fingerprint length (or algorithm) for the chunk-vendors and app assets?
Update:
I ended up forcing assets hash change by modifying the loader's hashType option in vue.config.js(which seem to default to 'md5'):
module.exports = {
...
chainWebpack: config => {
config.module
.rule('vue')
.use('vue-loader')
.loader('vue-loader')
.tap(options => {
options.hashType = `sha1`
return options
})
},
I wasn't able to change the hash length. It seems to be hardcoded in #vue/cli-service": "^4.1.2"

CopyWebpackPlugin isn't copying static files to output directory

My files show as being emitted but they are not actually being copied to dist folder.
Excerpt of compilation log:
Version: webpack 4.15.1 Time: 1824ms Built at: 01/29/2020 3:51:51 PM
Asset Size Chunks Chunk Names
main.js 116 KiB 0 [emitted] main
CSS/main.css 76 bytes [emitted] Images/Uplink_Logo_Horiz.jpg 651 KiB [emitted] [big]
CSS/adminlte.css 708 KiB [emitted] [big]
index.html 6.7 KiB [emitted]
And my webpack config plugin looks like this:
plugins: [
new CopyWebpackPlugin([
{
from: './Images/**',
to: path.join(__dirname, 'dist'),
logLevel: 'trace'
},
{
from: './CSS/**',
to: path.join(__dirname, 'dist'),
logLevel: 'trace'
}
]),
new HtmlWebpackPlugin({
template: './src/index.html'
})
],
I tried changing the order of CopyWebpackPlugin & HtmlWebpackPlugin to no luck. Did you do any other thing to solve this other than just changing the order.
Versions:
"vue": "^2.6.11", "webpack": "^4.15.0", "webpack-cli": "^3.0.8",
"copy-webpack-plugin": "^5.1.1", "html-webpack-plugin": "^3.2.0",
Updated Image:
Full project structure:
Found out the issue. The static files were not included in the VS project. Once I included them it started working. Thanks, for the help :)

how to prevent mini-css-extract-plugin from creating a js entrypint

I am relatively new to express + webpack, so i am unclear wether this is intended or not, and if not, how to properly configure it. the question is around the additional asset & entry point created when using the mini-css-extract-plugin.
webpack config:
Extract = require('mini-css-extract-plugin');
path = require('path');
Write = require('write-file-webpack-plugin');
module.exports = {
mode: 'development',
entry: {
demo_scripts: path.resolve('server', 'scripts', 'demo.js'),
demo_styles: path.resolve('server', 'styles', 'demo.css')
},
output: {
path: path.resolve('.tmp'),
filename: '[name].js'
},
plugins: [new Write(), new Extract()],
module: {
rules: [
{
test: /\.js$/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['babel-preset-env']
}
}
]
},
{
test: /\.css/,
use: [
{
loader: Extract.loader
},
{
loader: 'css-loader'
}
]
}
]
}
};
webpack output
Asset Size Chunks Chunk Names
demo_scripts.js 3.91 KiB demo_scripts [emitted] demo_scripts
demo_styles.css 36 bytes demo_styles [emitted] demo_styles
demo_styles.js 3.89 KiB demo_styles [emitted] demo_styles
Entrypoint demo_scripts = demo_scripts.js
Entrypoint demo_styles = demo_styles.css demo_styles.js
my question is, why is demo_styles.js being created? although the css is being extracted, it almost seems like webpack is still creating a bundled js with css, but when i view that file, the only line in it is
eval("// extracted by mini-css-extract-plugin\n\n//# sourceURL=webpack:///./server/styles/demo.css?");
can anyone help explain what is going on here?
UPDATE
if i remove the demo_styles entry point, and configure it via the plugin init, no css asset is built.
({
plugins: [
new Write(),
new Extract({
filename: 'demo_styles.css'
})
]
});
Asset Size Chunks Chunk Names
demo_scripts.js 3.91 KiB demo_scripts [emitted] demo_scripts
Entrypoint demo_scripts = demo_scripts.js
the repo for this is here (note the express branch) https://github.com/brewster1134/bumper/tree/express
There are two workarounds for your problem. For both of them, you need to change the entry point of the Webpack configuration file. I, personally, prefer the first option.
Option 1:
Change the entry to the following:
entry: {
demo: [
path.resolve('server', 'scripts', 'demo.js'),
path.resolve('server', 'styles', 'demo.css'),
]
}
This will generate the following outputs (based on the filename you provided for Extract class and output section:
demo.js
demo_styles.css
Option 2:
For this option, you need to remove the CSS file from the entry point and import it inside the JS file:
webpack.config.js
...
entry: path.resolve('server', 'scripts', 'demo.js'),
...
demo.js
import './../styles.demo.css'
//rest of your JS codes
This solution will generate the same output as Option1
Webpack pulls everything into a js file, then MiniCssExtractPlugin takes it out of that file, leaving a blank js file with // extracted by mini-css-extract-plugin.
My solution is to group your css and js in the entry section of webpack.config.js
entry: {
demo: {
import: [ path.join("server", "scripts", "demo.js"), path.join("server", "styles", "demo.css") ],
filename: "demo.js", // outputs demo.js, demo.css to your output directory
},
main: {
import: [ path.join("server", "scripts", "main.js"), path.join("server", "styles", "main.css") ],
filename: "main.js", // outputs main.js, main.css to your output directory
},
}
Also, so naming works well, use this for your plugins section:
plugins: [
new MiniCssExtractPlugin({
filename: "[name].css"
}),
],
Adjust the bundles "demo" and "main", as well as paths accordingly.
Please remove demo_styles from your entry point this is creating demo_styles.js.
instead you can inject css file like this:
plugins: [
new MiniCssExtractPlugin({
filename: 'demo_styles.css',
}),
Let me know if the issue still persists, Happy to help