Vue CLI 3 service worker fails to register out of box - vue.js

I built my app using Vue CLI3 with PWA. When I build for production the service worker fails to register.
I then decided to check if it was something I did or Vue CLI 3 out the box. I built a brand new app, built it and deployed it to AWS s3 with cloudfront. Even the brand new app without any changes fails to register the service worker with error: "The script has an unsupported MIME type ('text/plain')." and "Error during service worker registration: DOMException"
I've tried quite a few things other than listed below that google search results suggested but I end up with the same error.
I tried using the vue.config.js to load a custom worker in which I just copied the contents of the one that vue produces in a build.
pwa: {
workboxPluginMode: 'InjectManifest',
workboxOptions: {
swSrc: 'public/service-worker.js'
},
themeColor: '#ffffff'
}
I have tried loading it from index.html also.
If I host it locally it registers without any issues
The file does get created and it's accessible from the console but for some odd reason unknown to me it does not want to register at all.
Has anyone had this problem before and how did you resolve this?
Hosted on AWS s3 & cloudfront with HTTPS enabled and using the default AWS certificates for testing.
$ vue --version
3.9.3
$ node --version
v12.7.0
$ npm --version
6.10.0
UPDATE
I found that when I upload to S3 using aws cli sync it changes all .js files content-type
Once I resolve this I will update my question again.

Related

Missing config.json stencil CLI

I'm trying to do some work for a client, but cannot get their bigcommerce site running locally. I have installed stencil CLI (v3.1.1) and downloaded the theme from the bigcommerce dashboard (all files). from the root of the theme i ran "stencil init", then "npm i" and "stencil start".
when i run stencil start, it throws an error saying there's no config.json file.
this is the error i get
How do i generate the config.json file?
The only config file I see is config.stencil.json.
I have also tried running "stencil pull" in hopes that it would pull the config, but it throws another error: "not ok -- Error: Could not fetch active theme details for channel 1: Request failed with status code 404"
Stencil-cli version:
3.1.1
Node version:
12
NPM version:
6.14.15
OS:
mac big sur
Stencil 3.1.1 has been deprecated for some time now. I believe the current version is 3.8. As of 4 months ago, anything below 3.5 will not run (https://developer.bigcommerce.com/changelog#publications/required-stencil-cli-version-set-to-3-5-0).
If you don't have a config.json file in your project, you will need to get the one from the client's store. Try downloading their theme again. It should come through.
Edit: It is possibly the case that you need a new API token. Try making a new one for your store. Make sure the following scopes are set:
Themes: Modify
Settings & Information: Modify
Sites & Routes: Read-only (or Modify)
Documentation for creating a new API account: https://support.bigcommerce.com/s/article/Store-API-Accounts#creating

"amplify publish" fails to deploy without any detailed error stack trace

We are using AWS amplify to develop our next.js application for the first time and trying manual deployment process. We are getting following error when we try to run "amplify publish".
This error is frustrating because there is no stack trace to figure out what is causing the issue. I can see the artifacts were successfully loaded to S3 bucket. But deployment fails.
Error:
Export successful
✔ Zipping artifacts completed.
✖ Deployment failed! Please report an issue on the Amplify Console GitHub issue tracker at https://github.com/aws-amplify/amplify-console/issues.
An error occurred during the publish operation
I tried to manually upload the zipped file using the "drag and drop". It feels like its stuck with the message Your build is being queued.... for hours now.
Any help is highly appreciated. This is a huge blocker for us.
I fixed this issue.
first run this command
amplify configure project
after set 'out' to Distribution Directory Path like this.
Distribution Directory Path: out
configurations.png
Try to put static content on S3 manually.
For example, if you have generated static contents in the dist/ directory using nuxt generate, run the following command:
aws s3 sync dist/ s3://{YOUR_BUCKET_NAME}
If this solves your problem then try to use CodeCommit for your amplify project until this gets fixed.
GitHub issue: https://github.com/aws-amplify/amplify-console/issues/1369
We resolved the above issue. The issue was with the IAM policies. Once we fixed the role policies we were able to publish and see the progress of the deployment.
https://docs.amplify.aws/guides/hosting/nextjs/q/platform/js/
1) SSG Only:
Inside package.json
"scripts": {
"build": "next build && next export",
...
}
Run this command.
amplify configure project
Then, keep every thing the way it is, except this:
Distribution Directory Path: out
2) SSG & SSR:
Inside package.json
"scripts": {
"build": "next build",
...
}
Run this command.
amplify configure project
Then, keep every thing the way it is, except this:
Distribution Directory Path: .next
Note:
Do not forget to change the Image in index.js, because currently AWS does not support next/image.
https://docs.amplify.aws/guides/hosting/nextjs/q/platform/js/#deploy-and-host-an-ssg-only-app

Spartacus API calls return 504 (Gateway Timeout) when running using Server Side Rendering (SSR)

I'm trying to get Spartacus to work with SSR. When opening the default URL, http://localhost:4200, the storefront renders, as expected, but only after I clear the site data first. When I attempt to browse the storefront, API calls fail with a 504 (Gateway timeout). Chrome dev tools indicates the error is happening in the service worker. At this point, I'm wondering if I configured Spartacus incorrectly. When running Spartacus using yarn start rather than yarn serve:ssr, I can load the home page and browse the site normally.
OS: Ubuntu 16.04.6 LTS
Chrome Version: 73.0.3683.75
Node version: 11.15.0
Angular CLI version: 8.3.8
Yarn version: 1.19.1
ng new ssr-spartacus-app --style=scss
cd ssr-spartacus-app
ng add #spartacus/schematics --baseUrl https://localhost:9002 --baseSite cmssiteuid --pwa --ssr
rm src/app/app.component.html
echo "<cx-storefront>Loading...</cx-storefront>" > src/app/app.component.html
yarn build:ssr
yarn serve:ssr
Before running yarn build:ssr, I made following change to the app.module.ts file:
Before
context: {
baseSite: ['cmssiteuid'],
},
After
authentication: {
client_id: 'mobile_android',
client_secret: 'secret',
},
context: {
urlParameters: ['baseSite', 'language', 'currency'],
baseSite: ['cmssiteuid'],
},
I also set anonymousConsents to false. With this set to true, I was getting a lot of CORs errors.
If been scratching my head with this for a little while now and I'm hoping someone with more knowledge of Spartacus' inner workings can shed some light on why Spartacus is behaving this way with SSR.
I'm not sure that I can give you some certain recipe to fix the issue, obviously I need more details and logs relates to your problem, but still, based on my experience I can share with you some tips and tricks about how we should play with such issues (which relates to SSR).
Some set of theory which relates to SSR
https://angular.io/guide/universal (you can feel free to use Angular official documentation as a primary source, cuz Spartacus uses Angular OOTB features to make it works)
https://sap.github.io/spartacus-docs/server-side-rendering-in-spartacus/
https://enable.cx.sap.com/tag/tagid/spartacus (SSR related videos)
Practical approaches for debugging SSR
You should observe and analyze console output during starting your application in Node.js
You can use SSR configuration from example Storefront application (https://github.com/SAP/spartacus/tree/develop/projects/storefrontapp) like a starting point, cuz OOTB SSR works like a charm
Something from Spartacus team https://sap.github.io/spartacus-docs/how-to-debug-server-side-rendered-storefront/
Common set of theory to ensure that application has been configured correctly
SAP Commerce Cloud configuration for working with Spartacus https://sap.github.io/spartacus-docs/installing-sap-commerce-cloud/
Take a look on the guide https://sap.github.io/spartacus-docs/building-the-spartacus-storefront-from-libraries/ to ensure, that your frontend application has correct configuration
Double check your configuration which B2cStorefrontModule is using (here you can find an example project here https://github.com/SAP/spartacus/tree/develop/projects/storefrontapp)
Take a look on Network and Console browser tabs and try to resolve all errors
did you turn off PWA?
Turn PWA off.
As soon as Spartacus is installed in PWA mode, a service worker is installed, and it serves a cached version of index.html, along with the js files. This results in SSR being completely skipped. The following steps describe how to turn off PWA:
Check that there are no service workers registered in your app. If you do find any service workers, remove them.
Turn PWA off in your app module configuration, as follows:
StorefrontModule.withConfig({
backend: {
occ: {
baseUrl: 'https://[your_enpdoint],
},
},
pwa: {
enabled: false,
},
};
Rebuild your local Spartacus libraries by running the following command:
yarn build:core:lib
Build your local Spartacus shell app by running the following command:
yarn build --prod
Build the SSR version of your shell app by running the following command:
yarn build:ssr
Start Spartacus with the SSR server by running the following command:
yarn serve:ssr
If you are getting 504 after hitting the API service you need to check your API logs.
IF you have err log:
{"instant":{"epochSecond":1644915623,"nanoOfSecond":929833000},"thread":"hybrisHTTP1","level":"ERROR","loggerName":"org.springframework.web.servlet.DispatcherServlet","message":"Context initialization failed","thrown":{"commonElementCount":0,"localizedMessage":"Error creating bean with name 'cartEntriesController': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'defaultStockValidator' defined in ServletContext resource [/WEB-INF/config/v2/validators-v2-spring.xml]: Unsatisfied dependency expressed through constructor parameter 0: Could not convert argument value of type [de.hybris.platform.ycommercewebservices.stock.impl.DefaultCommerceStockFacade] to required type [de.hybris.platform.commercewebservices.core.stock.CommerceStockFacade]: Failed to convert value of type 'de.hybris.platform.ycommercewebservices.stock.impl.DefaultCommerceStockFacade' to required type 'de.hybris.platform.commercewebservices.core.stock.CommerceStockFacade'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'de.hybris.platform.ycommercewebservices.stock.impl.DefaultCommerceStockFacade' to required type 'de.hybris.platform.commercewebservices.core.stock.CommerceStockFacade': no matching editors or conversion strategy found","message":"Error creating bean with name 'cartEntriesController': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'defaultStockValidator'
You can try resolution:
Remove template extension ycommercewebservices extension from manifest.json, rebuild and redeploy with "Migrate Data" mode.

How can I reduce the webpack bundle size for a Vue.js / Nuxt.js project incorporating AWS SDK?

Summary:
I have created projects, with Vue.js and Nuxt.js, where I have installed aws-amplify (which automatically installs aws-sdk) in order that I can implement authentication with AWS Cognito.
In both cases, this works very nicely, but the problems come when I build production versions.
In both cases, I end up with massive bundle sizes which (thanks to webpack-bundle-analyzer) I can immediately see are caused by the aws-sdk which appears to contain code to implement every AWS service, under the sun, despite the fact that I am only importing AWS Cognito's: "Auth" (import { Auth } from 'aws-amplify')
I have tried creating a custom AWS SDK for JavaScript, which only includes the service: AWS.CognitoIdentity, but despite incorporating that (presumably incorrectly), I still end up with the same bundle size (and aws-sdk files) when I build the projects.
As I say, this is happening in both Nuxt and Vue project, but in order to simplify this, I for now just want to find the solution to a very basic sample project created with Vue.
I think I must be doing something dumb, but I can't work out what that is.
Any help would be greatly appreciated! :-)
Steps to reproduce:
Create a basic Vue.js project with defaults. Run: vue create vue-aws-sdk-inv
[Note: Steps 2 - 4, are not crucial to reproduce issue, but install webpack-bundle-analyzer which provides useful extra info.]
In the new project, install webpack-bundle-analyzer. Run: npm install --save-dev webpack-bundle-analyzer
Create root file: vue.config.js
Add the following code to vue.config.js:
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer")
.BundleAnalyzerPlugin;
module.exports = {
configureWebpack: {
plugins: [new BundleAnalyzerPlugin()]
}
};
As a benchmark, build the project. Run: npm run build
At this stage, the project will build (with no console warnings) and webpack-bundle-analyzer will launch (in the browser) showing the file: chunk-vendors..js, at the top of the tree, containing a bunch of other .js files, all of acceptable size.
Install AWS Amplify (and by default aws-sdk). Run: npm i aws-amplify
Open src/components/HelloWorld.vue and add the following under the tag: import { Auth } from "aws-amplify";
Build the project. Run: npm run build
At this stage, the project will build WITH console warnings regarding the following files being too large:
File Size Gzipped
dist/js/chunk-vendors.013ac3f0.js 3055.78 KiB 550.49 KiB
dist/js/app.fa2a21c4.js 4.67 KiB 1.67 KiB
dist/css/app.53019c4c.css 0.33 KiB 0.23 KiB
If installed, webpack-bundle-analyzer should launch (in the browser) showing an inflated: chunk-vendors..js, due to a hefty: aws-sdk.
aws-sdk will include api: .json files and lib: .js files for every AWS service I can think of!
The attempt to rectify:
Navigate to: https://sdk.amazonaws.com/builder/js/
Clear all services.
Select just: AWS.CognitoIdentity
Download "Minified" aws-sdk-.js
Download "Default" aws-sdk-.min.js
[Note: the following are the steps I am guessing I'm getting wrong?...]
In the project, search the node_modules directory for aws-sdk.js and aws-sdk.min.js.
They were found in /node_modules/aws-sdk/dist
Replace both files with the downloaded files (renaming to aws-sdk.js and aws-sdk.min.js respectively.)
Build the project. Run: npm run build
Project will build with same console warnings and same massive aws-sdk, as before, containing all the same .js and .json files for a bunch of services that are not actually imported in the application.
Final pieces of analysis:
Remove aws-sdk.js and aws-sdk.min.js from project's: /node_modules/aws-sdk/dist
Build the project. Run: npm run build
Project is built without even referencing these files.
Rename /node_modules/aws-sdk to /node_modules/TEMP_aws-sdk and attempt to build the project.
Build fails, and this proves (I think) that I was at least trying to add the custom versions, of aws-sdk.js and aws-sdk.min.js, somewhere in the correct directory!
Source Code:
vue.config.js:
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer")
.BundleAnalyzerPlugin;
module.exports = {
configureWebpack: {
plugins: [new BundleAnalyzerPlugin()]
}
};
src/components/HelloWorld.vue:
import { Auth } from "aws-amplify";
As said before, any help would be greatly appreciated! :-)
It looks like import { Auth } from "aws-amplify"; doesn't currently allow for tree shaking according to this issue.
Reading through several related issues, it appears that:
import Auth from '#aws-amplify/auth';
is the best you can currently do. I suspect that over time, the AWS team will figure out a way to better separate the internals.
For readers looking for a way to reduce bundle sizes for the aws-sdk package, see this section of the docs.
In my case:
import S3 from 'aws-sdk/clients/s3';
import AWS from 'aws-sdk/global';
cut the bundle size down by quite a lot. That gets it down to ~57k gz to use S3.
Also, for anyone using nuxt you can just run nuxt build -a to get the build analyzer.

How run Angular2 (front-end) and Symfony3 (back-end API) together in development zone?

This is my first question here. I have already spent hours reading topics, but never posted a question before.
At this moment I am developping an Angular4 application. I am running my app with "ng build --watch" and a local PHP webserver pointed to the 'dist' folder of my angular app. (When using build-in liveload server 'ng serve' there isn't a PHP server available, so i fixed this with 'ng build --watch' and a local PHP build-in server of PHPStorm)
To communicate with my MYSQL database, I used before single-php files in a directory called '/api'. I added this folder to my assets in the angular-cli.json file, so the API folder is also being pushed to the 'dist' folder when running the app local.
In this case, I was able to use relative paths to point my http requests. (like a POST action to '/api/insert.php'). So when publishing my app, it was not necessary to modify the paths of my HTTP requests.
But now I would like to use a backend framework, after some research I found http://api-platform.com, a PHP framework builded on Symfony3. When i am running this API, this runs for example on localhost:8000 while my angular applciation runs on localhost:4200.
So, that means i would have to use absolute paths for my HTTP requests. (eq http://localhost:8000/api/insert.php instead of /api/insert.php).
At this moment I have 2 projects: one front-end and one back-end. To make developping faster, easier, and simpler I would like to put both projects together. I know some developpers don't like this way of architecture, but in my case it is the best solution, one project, with a front and back-end included.
Concrete: Is it possible to run a debug-webserver in development zone with my angular app running on eq localhost and my symfony3/api-platform on eq localhost/api on the same time, same domain, and same port?
I would like to keep this project folder structure to keep it clean:
- projectname (root)
--- frontend
----- (all directories/files from angular)
--- backend
----- (all directories from api-platform / symfony3)
Sincerely,
Lander
running both application on the same domain (f.ex. localhost) is no problem, but they need to run on different ports. In your case angular is running on 4200 and your PHP application on 8000. You can configure angular with a proxy, which passes requests to http://localhost:4200/api to http://localhost:8000/api
In your angular root directory (where your package.json is), create a file proxy.conf.json
{
"/api": {
"target": "http://localhost:8000",
"secure": false
}
}
then change your package.json to use this proxy:
"scripts": {
"ng": "ng",
"start": "ng serve --proxy-config proxy.conf.json",
// other scripts
}
now run the webpack server with npm start instead of ng serve
Personally, I git ignore the proxy.conf.json, because some colleagues run their backend on a different port. Therefore we created a proxy.conf.dist.json with the above contents in git. If you want to use a different port, you can just copy it and change the port, while those, who want to use the default, can simply symlink to it.
UPDATE:
We recently switched to another method, namely using environment configurations.
By default, Angular has a dev and prod environment, specified in the .angular-cli.json
"environments": {
"dev": "environments/environment.ts",
"prod": "environments/environment.prod.ts"
}
In these files, specify the API path:
environment.ts
export const environment = {
production: false,
apiUrl: '//localhost:8000'
};
environment.prod.ts
export const environment = {
production: true,
apiUrl: '//my-api-domain.tld'
};
You can add as many environments as you want (f.ex. for tests, beta, etc.). In angular, you can use the environment by importing it:
import {environment} from '../environments/environment';
But I suggest creating a config service following this answer: https://stackoverflow.com/a/43193574/7933618
I ended up by using another backend. In my case an nodeJS server was the best, fast and most simple solution.