Webpack dev middleware react hot reload too slow - express

I have a simple configuration with webpack-dev-middleware and webpack-hot-middleware that uses Hot reload (HMR) with react.
Everything is working fine except that every change i made to the code it takes up 2 3-4 seconds !!! till I see it in the browser.
Am I doing something wrong ? it's supposed to be like this ?
My code is rather big and my bundle minified get to 841kb (200kb gzipped) is this the reason ? the more the codebase is bigger the bundle creation in slower?
Express Server:
var webpack = require('webpack');
var webpackConfig = require('./webpack.hot.config');
var compiler = webpack(webpackConfig);
app.use(require("webpack-dev-middleware")(compiler, {
noInfo: true,
publicPath: webpackConfig.output.publicPath,
watchOptions: {
poll: true
}
}));
app.use(require("webpack-hot-middleware")(compiler, {
log: console.log,
path: '/__webpack_hmr',
heartbeat: 10 * 1000
}));
webpack.hot.config.js
const path = require('path');
const webpack = require('webpack');
module.exports = {
context: __dirname,
entry: [
'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000',
'./src/js/index'
],
module: {
loaders: [{
test: /\.jsx?$/,
include: path.join(__dirname, 'src/js'),
//exclude: /node_modules/,
loader: 'react-hot!babel'
},
{
// Test expects a RegExp! Note the slashes!
test: /\.css$/,
loaders: ['style', 'css'],
// Include accepts either a path or an array of paths.
include: path.join(__dirname, 'src/css')
}
]
},
resolve: {
extensions: ['', '.js', '.jsx']
},
output: {
path: __dirname + '/public',
publicPath: '/',
filename: 'js/app.js'
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
]
};
And this is what i get in the console when i changed something in the code:
[HMR] App is up to date.
app.js:73223 [HMR] bundle rebuilding
app.js:73226 [HMR] bundle rebuilt in 335ms
app.js:73289 [HMR] Checking for updates on the server...
app.js:73362 [HMR] Updated modules:
app.js:73364 [HMR] - ./src/js/components/header.jsx
app.js:73369 [HMR] App is up to date.

Pro Tip: Change your mode in webpack.config.js to development. It defaults to production if you leave this property out, which means it does slow production stuff and makes your hot reloading suck.
module.exports = {
mode: 'development'
};

Consider switching polling to false in your middleware. I've found that polling can be CPU-intensive.
In you webpack config, you might also want to try adding devtool: false to avoid creating a source map.

You should enable caching:
...
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
cache: true
};

Related

Production config Webpack build for a Rust, WebAssembly app to apache2 server

I have a Rust, Web assembly wasm app I need to deploy to an apache server. When upload the build, it doesn't run the software, it just shows a list of the files.
The build files look like this:
build
-0.bootstrap.js
-bootstap.js
-gfdgjkljlkjjiojohio.module.wasm
my webpack config looks like
const path = require('path');
module.exports = {
entry: "./bootstrap.js",
output: {
path: path.resolve(__dirname, "dist"),
filename: "bootstrap.js",
},
mode: "development",
devServer: {
//host: "0.0.0.0",
port: 8080,
}
};
Where boostrap.js imports the main index.js file
// A dependency graph that contains any wasm must all be imported
// asynchronously. This `bootstrap.js` file does the single async import, so
// that no one else needs to worry about it again.
import("./index.js")
.catch(e => console.error("Error importing `index.js`:", e));
But when I deploy to my apache server, to my domain, I don't get the software running.
Why isn't it running?
I had to use HtmlWebpackPlugin and change my webpack config to this
module.exports = {
entry: './bootstrap.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
filename: 'index.html',
inject: true,
template: path.resolve(__dirname, 'index.html'),
}),
]
}

Webpack and Jquery - $ is not defined

Working first time on using Webpack in a ASP.Net Core project and running in to an issue bundling jQuery
$ is not defined
webpack.config.json
const path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const bundleFileName = 'bundle';
const dirName = 'wwwroot/dist';
module.exports = (env, argv) => {
return {
mode: argv.mode === "production" ? "production" : "development",
entry: ['./node_modules/bootstrap/dist/js/bootstrap.bundle.js', './wwwroot/js/site.js', './wwwroot/scss/site.scss'],
output: {
filename: bundleFileName + '.js',
path: path.resolve(__dirname, dirName)
},
module: {
rules: [
{
test: /\.s[c|a]ss$/,
use:
[
'style-loader',
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader',
'sass-loader'
]
}
]
},
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
}),
new CleanWebpackPlugin(),
new MiniCssExtractPlugin({
filename: bundleFileName + '.css'
})
]
};
};
I have tried and exhausted all possible variations I could find on the internet without any luck.
Using npm run build during the .Net build process to create the bundles
"$ is not defined" means that at the time when your library tried to do something with jQuery, jQuery itself either wasn't loaded or loaded incorrectly. Make sure that jQuery loads correctly first, and only then can the rest of the code use this library. Usually it is enough to put a jQuery call before all other calls.

Avoid browser caching after deploy a Vuejs app

My Vuejs App did not update after deployment for production, every time require "Empty cache and hard reload" to get the updates, I tried a lot of solutions to apply versioning to generated files after build but none of them worked for me, I need a solution to apply new hash for all files after every single build, not just the updated ones.
My vue.config.js file content:
const path = require("path");
module.exports = {
publicPath: process.env.NODE_ENV === "production" ? "/" : "/",
runtimeCompiler: true,
configureWebpack: {
resolve: {
alias: {
// If using the runtime only build
// vue$: "vue/dist/vue.runtime.esm.js" // 'vue/dist/vue.runtime.common.js' for webpack 1
// Or if using full build of Vue (runtime + compiler)
vue$: 'vue/dist/vue.esm.js', // 'vue/dist/vue.common.js' for webpack 1
'#': path.resolve('src'),
src: path.resolve('src'),
assets: path.resolve('src/assets'),
components: path.resolve('src/components'),
services: path.resolve('src/services'),
}
},
output: {
filename: '[name].[hash].js',
},
},
chainWebpack: config => {
config.module
.rule("eslint")
.use("eslint-loader")
.tap(options => {
options.configFile = path.resolve(__dirname, ".eslintrc.js");
return options;
});
},
};
Thanks in advance.
Welcome to the Vue JS cache nightmare. Did you try changing the version value in your package.json? I use to increment the value on each release as per x.y.z semantinc versioning. Maybe doing something like this:
{
"name": "My app",
"version": "1.0.15",
"private": true,
...
}

Uncaught ReferenceError: webpackJsonp in Vue Js

I have suddenly started hitting Uncaught ReferenceError: webpackJsonp in Vue Js. I am fairly new to Js and have just started with Vue applications. I tried the various solutions that were mentioned in the Git and stackoverflow but they have not worked. Can someone help me out.
To give some context, the issue suddenly appeared without having made much of a change. The code is working when it was in the state earlier but making any change in the components even modifying the css has started causing the issue.
Based on what I read about the issue, it is supposed to be controlled by the webpack.prod.conf.js (Attached mine below). Incase any other info is needed please let me know.
"use strict";
const path = require("path");
const utils = require("./utils");
const webpack = require("webpack");
const config = require("../config");
const merge = require("webpack-merge");
const baseWebpackConfig = require("./webpack.base.conf");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const OptimizeCSSPlugin = require("optimize-css-assets-webpack-plugin");
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
const env = require("../config/prod.env");
const webpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({
sourceMap: config.build.productionSourceMap,
extract: true,
usePostCSS: true
})
},
devtool: config.build.productionSourceMap ? config.build.devtool : false,
output: {
path: config.build.assetsRoot,
filename: utils.assetsPath("js/[name].[chunkhash].js"),
chunkFilename: utils.assetsPath("js/[id].[chunkhash].js")
},
plugins: [
// http://vuejs.github.io/vue-loader/en/workflow/production.html
new webpack.DefinePlugin({
"process.env": env
}),
new UglifyJsPlugin({
uglifyOptions: {
compress: {
warnings: false
}
},
sourceMap: config.build.productionSourceMap,
parallel: true
}),
// extract css into its own file
new ExtractTextPlugin({
filename: utils.assetsPath("css/[name].[contenthash].css"),
// Setting the following option to `false` will not extract CSS from codesplit chunks.
// Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack.
// It's currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it's `false`,
// increasing file size: https://github.com/vuejs-templates/webpack/issues/1110
allChunks: true
}),
// Compress extracted CSS. We are using this plugin so that possible
// duplicated CSS from different components can be deduped.
new OptimizeCSSPlugin({
cssProcessorOptions: config.build.productionSourceMap ?
{ safe: true, map: { inline: false } } :
{ safe: true }
}),
// generate dist index.html with correct asset hash for caching.
// you can customize output by editing /index.html
// see https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: config.build.index,
template: "index.html",
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
// more options:
// https://github.com/kangax/html-minifier#options-quick-reference
},
// necessary to consistently work with multiple chunks via CommonsChunkPlugin
chunksSortMode: "dependency"
}),
// keep module.id stable when vendor modules does not change
new webpack.HashedModuleIdsPlugin(),
// enable scope hoisting
new webpack.optimize.ModuleConcatenationPlugin(),
// split vendor js into its own file
new webpack.optimize.CommonsChunkPlugin({
name: "vendor",
async: false,
minChunks(module) {
// any required modules inside node_modules are extracted to vendor
return (
module.resource &&
/\.js$/.test(module.resource) &&
module.resource.indexOf(path.join(__dirname, "../node_modules")) === 0
);
// return module.context && module.context.includes("node_modules");
}
}),
// This instance extracts shared chunks from code splitted chunks and bundles them
// in a separate chunk, similar to the vendor chunk
// see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk
new webpack.optimize.CommonsChunkPlugin({
name: "app",
async: "vendor-async",
children: true,
minChunks: 3
}),
// extract webpack runtime and module manifest to its own file in order to
// prevent vendor hash from being updated whenever app bundle is updated
new webpack.optimize.CommonsChunkPlugin({
name: "manifest",
async: false,
minChunks: Infinity
}),
// copy custom static assets
new CopyWebpackPlugin([{
from: path.resolve(__dirname, "../static"),
to: config.build.assetsSubDirectory,
ignore: [".*"]
}])
]
});
if (config.build.productionGzip) {
const CompressionWebpackPlugin = require("compression-webpack-plugin");
webpackConfig.plugins.push(
new CompressionWebpackPlugin({
asset: "[path].gz[query]",
algorithm: "gzip",
test: new RegExp(
"\\.(" + config.build.productionGzipExtensions.join("|") + ")$"
),
threshold: 10240,
minRatio: 0.8
})
);
}
if (config.build.bundleAnalyzerReport) {
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer")
.BundleAnalyzerPlugin;
webpackConfig.plugins.push(new BundleAnalyzerPlugin());
}
module.exports = webpackConfig;
The entry points are missing in the configuration, i.e. you are not informing webpack from where the application should start.
Also this issue is happening because you have mentioned vendor
please refer this link

Vue project (django + webpack) shows white screen when accessing ngrok on mobile

I'm trying to use ngrok to test my vue + django project on my mobile phone, and it isn't working (it just shows a white screen). The vue portion is served using webpack (v2, not the latest vue cli 3).
The funny thing is ngrok works when I access my vue project from my computer (or another colleague's computer) - it just doesn't work from a mobile phone. The http log shows a 200 response, just that it shows a white screen on my phone. In addition, accessing other none vue pages work, so it's probably a webpack issue.
I've tried setting disableHostCheck to true, but it still doesn't work, and I'm not sure what else to do.
webpack.config.js
const path = require('path')
const webpack = require('webpack')
const VueLoaderPlugin = require('vue-loader/lib/plugin')
const BundleTracker = require('webpack-bundle-tracker')
const WriteFilePlugin = require('write-file-webpack-plugin')
module.exports = {
entry: './src/main.js',
output: {
path: path.resolve(__dirname, './dist'),
publicPath: 'http://localhost:8080/dist/',
filename: 'build.js'
},
plugins: [
new BundleTracker({
filename: 'webpack-stats.json'
}),
new WriteFilePlugin(),
new VueLoaderPlugin()
],
devServer: {
historyApiFallback: true,
noInfo: true,
overlay: true,
// security risk to set to true, but need to turn it on for ngrok to work
disableHostCheck: true,
host: '0.0.0.0',
hot: true,
},
}
settings.py (django)
WEBPACK_LOADER = {
'DEFAULT': {
'CACHE': not DEBUG,
'BUNDLE_DIR_NAME': 'webpack_bundles/', # must end with slash
'STATS_FILE': os.path.join(str(BASE_DIR), 'frontend', 'webpack-stats.json'),
'POLL_INTERVAL': 0.1,
'TIMEOUT': None,
'IGNORE': [r'.+\.hot-update.js', r'.+\.map']
}
}