Browser cache problems with webpack chunks and vue.js components - javascript

The Problem
I have a problem with cached Vue.js components and I can't reproduce this problem on my devices but every client-side update we get users complains about broken interfaces and only clearing browser cache helps.
I use Laravel + Vue.js and it's multipage app.
Strategy
All components described in one file which included in app.js and it looks like this:
Vue.component('task-feed', () => import('./components/task/task-feed'/* webpackChunkName: "/js/components/task-feed" */));
Vue.component('task-item', () => import('./components/task/task-item'/* webpackChunkName: "/js/components/task-item" */));
There are vue.js async components.
And then i have configured webpack.mix like this:
let mix = require('laravel-mix');
const webpack = require('webpack');
const ChunkManifestPlugin = require('chunk-manifest-webpack-plugin');
const WebpackChunkHash = require('webpack-chunk-hash');
mix.disableNotifications();
let config = {
watchOptions: {
ignored: /node_modules/
},
resolve: {
alias: {
'vue$': mix.inProduction() ? 'vue/dist/vue.runtime.min.js' : 'vue/dist/vue.runtime.js',
}
},
output: {
chunkFilename: mix.inProduction() ? '[name].[chunkhash].js' : '[name].js',
},
plugins: [
new webpack.HashedModuleIdsPlugin(),
new WebpackChunkHash(),
new ChunkManifestPlugin({
filename: '/js/chunk-manifest.json',
manifestVariable: 'webpackManifest',
inlineManifest: true,
}),
],
};
mix.webpackConfig(config);
I'm using ChunkManifestPlugin here, that plugin creates chunk-manifest.json and i load it in the main layout like this:
window.webpackManifest = JSON.parse(#json(file_get_contents(public_path('/js/chunk-manifest.json'))));
Questions
What could be wrong here? Can anyone suggest the way to solve this?

In webpack.mix.js change it to this:
mix.config.webpackConfig.output = {
chunkFilename: 'scripts/[name].[chunkhash].js',
publicPath: '/',
};
Refer to this article for more information.

Configure webpack.mix.js to version your files
let version = 0;
mix.config.webpackConfig.output = {
chunkFilename: 'v/' + version + '/scripts/[name].js',
publicPath: '/',
};
mix.js('resources/js/app.js', 'public/v/'+version+'/js')
.sass('resources/sass/app.scss', 'public/v/'+version+'/css');

Related

after upgrade to Webpack 5 not able to access the menifest in copy-webpack-plugin

My config was working fine in webpack version 4.6.0 and webpack-assets-manifest version 3.1.1
since I upgraded to webpack 5 and webpack-assets-manifest to 5. I'm not getting value in my manifestObject it's just empty object
I suspect this is happening because transform function running before manifest is created
looked into the new documentation of webpack-assets-manifest but could not get it working
my goal is to access manifest value in transform function, but it looks like transform function is running before manifest is generated
var CopyWebpackPlugin = require('copy-webpack-plugin');
var SaveHashes = require('webpack-assets-manifest');
const manifest = new SaveHashes({
entrypoints: true,
entrypointsKey: 'entryPoints'
});
module.exports = {
entry: {
main: ['./src/apps/main'],
games: ['./src/apps/games'],
},
output: {
path: path.join(__dirname, 'dist'),
publicPath: assetsUrl,
filename: 'assets/javascript/[name].[contenthash].js',
chunkFilename: 'assets/javascript/[name].[contenthash].js'
},
.
.
.
.
.
plugins: [
new CleanWebpackPlugin(),
manifest,
new CopyWebpackPlugin([
{
from: './views/**/*',
to: path.join(__dirname, 'dist'),
transform(content, path) {
// I want to access manifest here
// so that I can inject the final script(javascript bundle with content hash)
// in my view template
const manifestObject = JSON.parse(manifest);
}
}
])
]
};
you need to export it like this
const ManifestPlugin = require("webpack-manifest-plugin").WebpackManifestPlugin;
.....
new ManifestPlugin({
fileName: "asset-manifest.json",
publicPath: paths.publicUrlOrPath,
generate: (seed, files, entrypoints) => {
const manifestFiles = files.reduce((manifest, file) => {
manifest[ file.name ] = file.path;
return manifest;
}, seed);
const entrypointFiles = entrypoints.main.filter(
(fileName) => !fileName.endsWith(".map")
);
return {
files: manifestFiles,
entrypoints: entrypointFiles,
};
},
}),
and it will work WebpackManifestPlugin is what you need

Load GLB model with Webpack - Three.js

I'm trying to use Webpack for the first time and I have trouble to add my glb model. My model is ok, used many times and I put in public folder. I dont' understand console error, any help will be appreciate, thanks.
I'm using three.js r116 and Firefox. Safari tell me same error, can't found the model.
Here a part of my JS code :
import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
const loader = new GLTFLoader();
loader.load('/assets/models/street_car.glb', (gltf) => {
scene.add(gltf.scene);
});
My webpack.config :
const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
entry: './src/scripts/main.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'dist/main.js',
},
performance: {
hints: false
},
plugins: [
new CopyWebpackPlugin([{ from: '**/*', to: '' }], {
context: 'src',
writeToDisk: true,
}),
],
devServer: {
contentBase: path.resolve(__dirname, 'dist'),
port: 9000,
historyApiFallback: true
}
};
And finally console error :
I just find the problem, add this lines to webpack.config
module:
{
rules:
[
{
test: /\.(glb|gltf)$/,
use:
[
{
loader: 'file-loader',
options:
{
outputPath: 'assets/models/'
}
}
]
},
]
}
And don't need to add assets in public folder, they are in my src folder with scripts.
For Webpack v5, the previous loaders are now obsolete (like file-loader, raw-loader, etc), and replaced by the use of Asset Modules
The correct asset module for 3d model formats like gltf, obj, fbx, stl etc. is asset/resource
I was looking for something like this but for a Symfony Webpack Encore application configuration. #MlleBz your answer actually helped me a lot, thanks.
So, with no further ado, if you're looking to implement a .glb or .gltf loader in a Symfony / React / ThreeJS application, add this to your webpack.config.js :
// add loader for .glb files (use this with three.js)
.addLoader({
test: /\.(glb|gltf)$/,
loader: 'file-loader'
})

Webpack DllPlugin with gulp: Cannot find module '... vendor-manifest.json'

I have a rather large React application built with webpack 2. The application is embedded into a Drupal site as a SPA within the existing site. The Drupal site has a complex gulp build setup and I can't replicate it with webpack, so I decided to keep it.
I have split my React application into multiple parts using the DllPlugin / DllReferencePlugin combo which is shipped out of the box in webpack 2. This works great, and I get a nice vendor-bundle when building with webpack.
The problem is when I try to run my webpack configuration in gulp, I get an error. I might be doing it wrong, as I have not been able to find much documentation on this approach, but nevertheless, it's not working for me.
It looks like it's trying to include the the manifest file from my vendor-bundle before creating it.
Whenever I run one of my defined gulp tasks, like gulp react-vendor I get an error, saying that it cannot resolve the vendor-manifest.json file.
If I on other hand run webpack --config=webpack.dll.js in my terminal, webpack compiles just fine and with no errors.
I have included what I think is the relevant files. Any help on this is appreciated.
webpack.config.js
// Use node.js built-in path module to avoid path issues across platforms.
const path = require('path');
const webpack = require('webpack');
// Set environment variable.
const production = process.env.NODE_ENV === "production";
const appSource = path.join(__dirname, 'react/src/');
const buildPath = path.join(__dirname, 'react/build/');
const ReactConfig = {
entry: [
'./react/src/index.jsx'
],
output: {
path: buildPath,
publicPath: buildPath,
filename: 'app.js'
},
module: {
rules: [
{
exclude: /(node_modules)/,
use: {
loader: "babel-loader?cacheDirectory=true",
options: {
presets: ["react", "es2015", "stage-0"]
},
},
},
],
},
resolve: {
modules: [
path.join(__dirname, 'node_modules'),
'./react/src/'
],
extensions: ['.js', '.jsx', '.es6'],
},
context: __dirname,
devServer: {
historyApiFallback: true,
contentBase: appSource
},
// TODO: Split plugins based on prod and dev builds.
plugins: [
new webpack.DllReferencePlugin({
context: path.join(__dirname, "react", "src"),
manifest: require(path.join(__dirname, "react", "vendors", "vendor-manifest.json"))
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
filename: 'webpack-loader.js'
}),
]
};
// Add environment specific configuration.
if (production) {
ReactConfig.plugins.push(
new webpack.optimize.UglifyJsPlugin()
);
}
module.exports = [ReactConfig];
webpack.dll.js
const path = require("path");
const webpack = require("webpack");
const production = process.env.NODE_ENV === "production";
const DllConfig = {
entry: {
vendor: [path.join(__dirname, "react", "vendors", "vendors.js")]
},
output: {
path: path.join(__dirname, "react", "vendors"),
filename: "dll.[name].js",
library: "[name]"
},
plugins: [
new webpack.DllPlugin({
path: path.join(__dirname, "react", "vendors", "[name]-manifest.json"),
name: "[name]",
context: path.resolve(__dirname, "react", "src")
}),
// Resolve warning message related to the 'fetch' node_module.
new webpack.IgnorePlugin(/\/iconv-loader$/),
],
resolve: {
modules: [
path.join(__dirname, 'node_modules'),
],
extensions: ['.js', '.jsx', '.es6'],
},
// Added to resolve a dependency issue in this build #https://github.com/hapijs/joi/issues/665
node: {
net: 'empty',
tls: 'empty',
dns: 'empty'
}
};
if (production) {
DllConfig.plugins.push(
new webpack.optimize.UglifyJsPlugin()
);
}
module.exports = [DllConfig];
vendors.js (to determine what to add to the Dll)
require("react");
require("react-bootstrap");
require("react-dom");
require("react-redux");
require("react-router-dom");
require("redux");
require("redux-form");
require("redux-promise");
require("redux-thunk");
require("classnames");
require("whatwg-fetch");
require("fetch");
require("prop-types");
require("url");
require("validator");
gulpfile.js
'use strict';
const gulp = require('gulp');
const webpack = require ('webpack');
const reactConfig = require('./webpack.config.js');
const vendorConfig = require('./webpack.dll.js');
// React webpack source build.
gulp.task('react-src', function (callback) {
webpack(reactConfig, function (err, stats) {
callback();
})
});
// React webpack vendor build.
gulp.task('react-vendor', function (callback) {
webpack(vendorConfig, function (err, stats) {
callback();
})
});
// Full webpack react build.
gulp.task('react-full', ['react-vendor', 'react-src']);
NOTE:
If I build my vendor-bundle with the terminal with webpack --config=webpack.dll.js first and it creates the vendor-manifest.json file, I can then subsequently successfully run my gulp tasks with no issues.
This is not very helpful though, as this still will not allow me to use webpack with gulp, as I intend to clean the build before new builds run.
I ended up using the solution mentioned in the end of my question. I build my DLL file first and then I can successfully run my gulp webpack tasks.
One change that can make it easier to debug the issue, is to use the Gulp utility module (gulp-util) to show any webpack errors that might show up during build of webpack, using gulp.
My final gulp setup ended up looking like this:
gulpfile.js
'use strict';
const gulp = require('gulp');
const gutil = require('gulp-util');
const webpack = require('webpack');
const reactConfig = require('./webpack.config.js');
const vendorConfig = require('./webpack.dll.js');
// React webpack source build.
gulp.task('react', function (callback) {
webpack(reactConfig, function (err, stats) {
if (err) {
throw new gutil.PluginError('webpack', err);
}
else {
gutil.log('[webpack]', stats.toString());
}
callback();
});
});
// React webpack vendor build.
gulp.task('react-vendor', function (callback) {
webpack(vendorConfig, function (err, stats) {
if (err) {
throw new gutil.PluginError('webpack', err);
}
else {
gutil.log('[webpack]', stats.toString());
}
callback();
});
});
// React: Rebuilds both source and vendor in the right order.
gulp.task('react-full', ['react-vendor'], function () {
gulp.start('react');
});
I hope this might help someone in a similar situation.
Whenever I run one of my defined gulp tasks, like gulp react-vendor I get an error, saying that it cannot resolve the vendor-manifest.json file.
Your gulpfile.js contains this:
const reactConfig = require('./webpack.config.js');
const vendorConfig = require('./webpack.dll.js');
And webpack.config.js contains this:
new webpack.DllReferencePlugin({
context: path.join(__dirname, "react", "src"),
manifest: require(path.join(__dirname, "react", "vendors", "vendor-manifest.json"))
}),
The require() calls are currently all executed immediately. Whenever you run Gulp, it will evaluate both Webpack configuration files. As currently configured, Node runs the code in webpack.config.js at startup, and from there it sees the require() used in your creation of the DllReferencePlugin, so it will also try to read manifest.json at that time and turn it into an object...which is before it has been built.
You can solve this in one of two ways:
The DllReferencePlugin's manifest option supports either an object (which is what you are currently providing), or else a string containing the path of the manifest file. In other words, it should work if you remove the require() from around your path.join(...) call.
Alternatively, you can also defer the loading of the Webpack config files. Moving your const reactConfig = require('./webpack.config.js'); from the top of the file directly into the gulp task function should be sufficient, assuming that this function is not invoked until after the manifest has been built.

Optimal webpack.config with webpack 2 for AngularJS 1.x app?

I want to set up an Angular 1.x app from scratch using webpack 2.
I am having trouble finding the best configuration for webpack.config, with optimal entry and output for production (meaning, all code, style and templating minified and gziped with no code repetition).
My main problem is how to set up webpack.config so that it recognizes all partials within the folder structure of my project, like these:
My current config file, for reference (which can't see subfolders):
var HtmlWebpackPlugin = require( 'html-webpack-plugin' );
var ExtractTextPlugin = require( 'extract-text-webpack-plugin' );
var path = require( 'path' );
module.exports = {
devServer: {
compress: true,
contentBase: path.join( __dirname, '/dist' ),
open: true,
port: 9000,
stats: 'errors-only'
},
entry: './src/app.js',
output: {
path: path.join( __dirname, '/dist' ),
filename: 'app.bundle.js'
},
module: {
rules: [ {
test: /\.scss$/,
use: ExtractTextPlugin.extract( {
fallback: 'style-loader',
use: [
'css-loader',
'sass-loader'
],
publicPath: '/dist'
} )
} ]
},
plugins: [
new HtmlWebpackPlugin( {
hash: true,
minify: { collapseWhitespace: true },
template: './src/index.html',
title: 'Prov'
} ),
new ExtractTextPlugin( {
filename: 'main.css',
allChunks: true
} )
]
};
Note that this isn't an exhaustive solution, as there are many optimizations one can make in the frontend, and I've kept the code snippets fairly short.
With webpack, there are a few routes that you can take to include partials into your app.js.
Solution 1
You can import/require your partials within app.js as such:
app.js
var angular = require('angular');
var proverbList = require('./proverb/list/proverb.list');
// require other components
// set up your app as normal
This allows the app.bundle.js to include your component js files in the main bundle. You can also use html-loader to include templates in the final bundle.
This isn't ideal, as all it does is create a large bundle.js (which doesn't leverage multiple downloads with http2 nor does it allow loading of components/files when the user explicitly requires it).
Solution 2
Importing partials as separate entry files into your webpack bundle:
webpack.config.js
const globby = require('globby');
const sourceDir = 'src';
var webpackentry = {
app: `${__dirname}/src/app.js`
};
const glob = globby.sync(`${__dirname}/${sourceDir}/**/*.js`)
.map((file)=>{
let name = file.split('/').pop().replace('.js', '');
webpackentry[name] = file;
});
const config = {
entry: webpackentry,
...
}
The second solution is unorthodox but it can be useful if you wanted to split all your partials as <script> tags in your html (for example if your company/team uses that as a means to include your directive/components/controllers), or if you have an app-2.bundle.js.
Solution 3
Use CommonsChunkPlugin:
webpack.config.js
let webpackentry = {
vendor: [
'module1',
'module2',
'module3',
]
}
...
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: ['vendor'] //... add other modules
})
]
CommonsChunkPlugin allows webpack to scrawl through your entry files and discern common modules that are shared among them. This means that even if you are importing module1 in different files, they will be compiled only once in your final bundle.

How to auto refresh browser with webpack on change?

I have a this file backend-dev.js which is mostly webpack configuration. I use it to run my express server from the bundled file. It stays on and restarts the server on any change. Is there any possible configuration can be added to auto refresh the browser too whenever I change the code?
This is what I have in the backend-dev.js:
const path = require('path');
const webpack = require('webpack');
const spawn = require('child_process').spawn;
const HtmlWebpackPlugin = require('html-webpack-plugin');
const compiler = webpack({
// add your webpack configuration here
entry: './app.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: "bundle.js"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['env', 'es2015', 'stage-2']
}
}
}
]
},
/*plugins: [
new HtmlWebpackPlugin({
title: 'Project Demo',
hash: true,
template: './views/index.ejs' // Load a custom template (ejs by default see the FAQ for details)
})
],*/
node: {
__dirname: false
},
target: 'node'
});
const watchConfig = {
// compiler watch configuration
// see https://webpack.js.org/configuration/watch/
aggregateTimeout: 300,
poll: 1000
};
let serverControl;
compiler.watch(watchConfig, (err, stats) => {
if (err) {
console.error(err.stack || err);
if (err.details) {
console.error(err.details);
}
return;
}
const info = stats.toJson();
if (stats.hasErrors()) {
info.errors.forEach(message => console.log(message));
return;
}
if (stats.hasWarnings()) {
info.warnings.forEach(message => console.log(message));
}
if (serverControl) {
serverControl.kill();
}
// change filename to the relative path to the bundle created by webpack, if necessary(choose what to run)
serverControl = spawn('node', [path.resolve(__dirname, 'dist/bundle.js')]);
serverControl.stdout.on('data', data => console.log(data.toString()));
serverControl.stderr.on('data', data => console.error(data.toString()));
});
Excellent question: I solved it in the following way:
express has two modules you can install to refresh in hot without refreshing the browser, and it will refresh automatically: I leave you my configuration.
npm i livereload
npm i connect-livereload
const livereload = require('livereload');
const connectLivereload = require('connect-livereload');
const liveReloadServer = livereload.createServer();
liveReloadServer.watch(path.join(__dirname, '..', 'dist', 'frontend'));
const app = express();
app.use(connectLivereload());
Note that the folder you want to monitor is in dist/frontend. Change the folder you want to monitor so that it works: To monitor the backend I am using NODEMON
livereload open a port for the browser in the backend to expose the changes: how does the connection happen? It's easy; express with "connect-livereload" and inject a script that monitors that port: if a change occurs, the browser is notified by express, and the browser will refresh for you.
I leave The information as simple as possible to test, and I do not recommend using it like this: To use it you must separate the development and production environments. I keep it simple so that it is easy to understand.
Here I leave the most relevant link I found: I hope it will be helpful too.
https://bytearcher.com/articles/refresh-changes-browser-express-livereload-nodemon/

Categories

Resources