I'm using Nuxt.js framework and my WorkBox config looks like below
workbox: {
workboxURL: 'https://cdn.jsdelivr.net/npm/workbox-sw#4.3.1/build/workbox-sw.min.js',
cacheAssets: false,
offline: false,
runtimeCaching: [
{
urlPattern: '^/$|/(?:about|contact)$',
handler: 'cacheFirst',
strategyOptions: {
cacheName: 'test-cache-v1',
cacheExpiration: {
maxEntries: 5,
maxAgeSeconds: 10
}
}
},
{
urlPattern: '/.*',
handler: 'networkOnly',
},
]
}
Here urlPattern: '^/$|/(?:about|contact)$' suppose to match all 3 requests:
/
/about
/contact
But only /about and /contact is matched and / is being handled by next cache strategy urlPattern: '/.*' which is networkOnly.
Not sure why WorkBox is not able to handle / request in cacheFirst strategy
This what ServiceWork.js file content looks like
workbox.routing.registerRoute(new RegExp('^/$|/(?:about|contact)$'), workbox.strategies.cacheFirst({"cacheName":"test-cache-v1","cacheExpiration":{"maxEntries":5,"maxAgeSeconds":10}}), 'GET')
workbox.routing.registerRoute(new RegExp('/.*'), workbox.strategies.networkOnly({}), 'GET')
WorkBox is running RegExp on event.request.url which returns full URL like http://localhost:3000 instead of relative path.
So wildcard ^/$ was not able to handle the request. I fixed the issue by replacing my RegExp from ^/$ to ^http://localhost:3000[/]?$
Related
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
When I generate Nuxtjs on SPA mode (SSR: false) nuxt generated dist without index.html file.
So I have two problems
1st: I need to redirect to lang folder ex. exmple.com redirect to exmaple.com/{locale}
2nd: I need to redirect for sub-pages ex. exmple.com/admin redirect to exmaple.com/{locale}/admin
// nuxt.config.js
...
i18n: {
lazy: true,
langDir: 'lang/',
locales: [
{
code: 'en',
iso: 'en-US',
file: 'en.js',
name: 'English'
},
{
code: 'ar',
iso: 'ar-EG',
file: 'ar.js',
name: 'عربى'
}
],
defaultLocale: {
locale: 'en',
prefix: true
},
...
I got an idea to solve this problem but I did not know if it is the best solution.
Just using .htaccess to handle requests and return which index I need.
I am running a VUE 3 CLI project on localhost
There is a remote server I need to call for data. Browsers were blocking this CORS so I had to learn how to set up correct api headers and a proxy in the vue config.
My vue.config.js file contains this:
devServer: {
https: true,
proxy: {
'^/api': {
target: 'https://api.mysite.com/',
ws: true,
changeOrigin: true
}
}
},
This resolved my CORS block from local host to the remote server but caused the problem in the title. It now thinks that the call to the sockjs-node file is cross origin.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://192.168.29.243:8080/sockjs-node/info?t=1615826901010. (Reason: CORS request did not succeed).
I can't seem to find any reason for this or a solution. Has anyone run into this and knows what to do?
This fixed it for me.
Please check following link: How can I fix these SockJS ssl errors?
// vue.config.js
module.exports = {
devServer: {
proxy: {
"^/api": {
target: "https://localhost:44345",
ws: true,
changeOrigin: true,
},
},
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept",
},
public: "http://localhost:44345",
disableHostCheck: true,
},
};
I am trying to run offline caching in Nuxt via the #nuxt/pwa package. It doesn't seen to register the service worker when I check the chrome devtool/application.
I am not sure if I am missing anything. Right now, I have only made the following additions to my nuxt.config file
pwa: {
icon: {
iconSrc: './static/logo.jpeg'
},
manifest: {
lang: 'en',
short_name: 'P',
name: 'Project',
start_url: '/',
display: 'standalone',
theme_color: '#00b5ad'
},
workbox: {
/* workbox options */
dev: false,
offlineStrategy: 'StaleWhileRevalidate',
runtimeCaching: [
{
urlPattern: 'https://media.giphy.com/media/.*',
handler: 'cacheFirst',
method: 'GET',
strategyOptions: {
cacheName: 'giphy',
cacheExpiration: {
maxEntries: 100,
maxAgeSeconds: 60 * 60 * 24 * 10
}
}
}
]
}
}
Along with this I have added '#nuxtjs/pwa' under modules.
I do notice that a sw.js file is being generated in the static file. But, nothing is being cached.
The sw.js looks as follows:
importScripts('https://cdn.jsdelivr.net/npm/workbox-cdn#4.3.1/workbox/workbox-sw.js')
// --------------------------------------------------
// Configure
// --------------------------------------------------
// Set workbox config
workbox.setConfig({
"debug": false
})
// Start controlling any existing clients as soon as it activates
workbox.core.clientsClaim()
// Skip over the SW waiting lifecycle stage
workbox.core.skipWaiting()
workbox.precaching.cleanupOutdatedCaches()
// --------------------------------------------------
// Precaches
// --------------------------------------------------
// Precache assets
// --------------------------------------------------
// Runtime Caching
// --------------------------------------------------
// Register route handlers for runtimeCaching
workbox.routing.registerRoute(new RegExp('https://media.giphy.com/media/.*'), new workbox.strategies.CacheFirst ({"cacheName":"giphy","cacheExpiration":{"maxEntries":100,"maxAgeSeconds":864000}}), 'GET')
workbox.routing.registerRoute(new RegExp('/_nuxt/'), new workbox.strategies.CacheFirst ({}), 'GET')
workbox.routing.registerRoute(new RegExp('/'), new workbox.strategies.StaleWhileRevalidate ({}), 'GET')
It's not recommended to test workbox on dev mode (npm run dev)
see doc: https://pwa.nuxtjs.org/modules/workbox.html#dev
You have to test in production mode with the localhost hostname.
So run your app with npm run build && npm run start and go to http://localhost:3000/
Then you should see this following message in your console panel:
[workbox] Welcome to Workbox! --- workbox-core.dev.js:132
BEFORE, I was using r.js to optimize and minify my javascript successfully. I had a main.js file that looked something like this:
require.config({
baseUrl: "scripts/lib",
paths: {
jquery: "http://code.jquery.com/jquery-1.11.2.min",
underscore: "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min",
d3: "d3-for-development",
katex: "https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.3.0/katex.min", // or 0.2.0
mathjax: "http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML&delayStartupUntil=configured",
etc...
},
shim: {
underscore: { exports: "_" },
chosen: { deps: ["jquery"] },
mathjax: {
exports: "MathJax",
init: function (){
MathJax.Hub.Config({
tex2jax: {
inlineMath: [['$','$'], ['\\(','\\)']],
processEscapes: true,
},
});
MathJax.Hub.Startup.onload();
return MathJax;
}
},
},
});
require( [
"jquery",
"underscore",
"browser-detect",
"check-types",
"katex",
"mathjax",
etc
], function(
$,
_,
browser,
check,
katex,
mathjax,
etc
){
/////////////////////////// INITIALIZATION ///////////////////////////
loginInit()
show('#login')
etc...
and I could successfully run node build/r.js -o mainConfigFile=www/scripts/main.js baseUrl=www/scripts/lib name=../main out=www/scripts/main-optimized.min.js generateSourceMap=true preserveLicenseComments=false optimize=uglify2 to minify. Everything worked.
NOW, I have a config.js file that looks like this:
require.config({
urlArgs: "bust=" + new Date().getTime(),
baseUrl: "scripts/lib",
paths: {
jquery: ["jquery-min", "http://code.jquery.com/jquery-1.11.2.min"],
underscore: ["underscore-min", "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min"],
d3: "d3-for-development", // if we add patches separately, then we can just use https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min
katex: ["katex-min", "https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.3.0/katex.min"], // or 0.2.0
mathjax: "http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML&delayStartupUntil=configured",
main: "../main",
etc...
},
shim: {
underscore: { exports: "_" },
chosen: { deps: ["jquery"] },
mathjax: {
exports: "MathJax",
init: function init() {
MathJax.Hub.Config({
tex2jax: {
inlineMath: [['$', '$'], ['\\(', '\\)']],
processEscapes: true }
});
MathJax.Hub.Startup.onload();
return MathJax;
}
}
}
});
require(["main"], function (main) {
// pass. by loading main, we run main.js
});
Instead of passing the minify/optimize arguments straight into the command line, I've created a rbuild.js file for that:
({
mainConfigFile: "../www/scripts/config.js",
baseUrl: "../www/scripts/lib",
name: "../config",
out: "../www/scripts/config-optimized.min.js",
generateSourceMap: true,
preserveLicenseComments: false, // this is necessary for generateSourceMap to work
optimize: "uglify2",
// removeCombined: true,
// findNestedDependencies: true,
paths: {
// https://github.com/jrburke/requirejs/issues/791
// http://www.anthb.com/2014/07/04/optimising-requirejs-with-cdn-fallback
jquery: "jquery-min",
underscore: "underscore-min",
d3: "d3-for-development",
katex: "katex-min",
mathjax: "http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML&delayStartupUntil=configured",
marked: "marked",
chosen: "chosen-min",
jsnetworkx: "jsnetworkx-min",
main: "../main",
},
})
and I run it with node build/r.js -o build/rbuild.js in the command line. It appears to run successfully and makes the config-optimized.min.js file, as expected. The output is:
Tracing dependencies for: ../config
Cannot optimize network URL, skipping: http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML&delayStartupUntil=configured
Uglify2 file: /Users/Matthew/programming/prove-math/www/scripts/config-optimized.min.js
/Users/Matthew/programming/prove-math/www/scripts/config-optimized.min.js
----------------
/Users/Matthew/programming/prove-math/www/scripts/lib/jquery-min.js
/Users/Matthew/programming/prove-math/www/scripts/lib/underscore-min.js
/Users/Matthew/programming/prove-math/www/scripts/lib/browser-detect.js
/Users/Matthew/programming/prove-math/www/scripts/lib/check-types.js
/Users/Matthew/programming/prove-math/www/scripts/lib/katex-min.js
/Users/Matthew/programming/prove-math/www/scripts/lib/profile.js
/Users/Matthew/programming/prove-math/www/scripts/lib/marked.js
/Users/Matthew/programming/prove-math/www/scripts/lib/d3-for-development.js
/Users/Matthew/programming/prove-math/www/scripts/lib/user.js
/Users/Matthew/programming/prove-math/www/scripts/lib/graph-animation.js
/Users/Matthew/programming/prove-math/www/scripts/lib/graph.js
/Users/Matthew/programming/prove-math/www/scripts/lib/node.js
/Users/Matthew/programming/prove-math/www/scripts/lib/blinds.js
/Users/Matthew/programming/prove-math/www/scripts/lib/chosen-min.js
/Users/Matthew/programming/prove-math/www/scripts/main.js
/Users/Matthew/programming/prove-math/www/scripts/lib/../config.js
But when I visit index.html via my server, the page is blank. The JS console gives no errors or log messages, which suggests that no JS is being run. My server gives no errors, which suggests that everything has been sent to the client successfully, and the client JS is not running.
So I'm pretty convinced the JS is there but not running. Is there something wrong with my setup that causes config.js to not run the code? With no error messages, I am having trouble troubleshooting :)
So I commented out
generateSourceMap: true,
preserveLicenseComments: false, // this is necessary for generateSourceMap to work
optimize: "uglify2",
and it worked! THEN, I uncommented that stuff, and it STILL worked!
It seems that as of requireJS 2.2 (I was using RequireJS 2.1.6 BEFORE), you can now use
optimize: "uglify",
or nothing at all, since this is the default setting. As of requireJS 2.2, it DOES use uglify2 in this case. This is the closest thing to an explanation that I can give :/