Firebase Cloud Messaging SW integration with Svelte-Kit - firebase

Has anyone integrated Firebase Cloud Messaging with Svelte-Kit. My main issue is registering the firebase-messaging-sw.js. If placed in the static directory I get a 'Syntax Error for using import outside of a module'. I've tried adding the file to the src directory, and telling vite about it. My svelte.config.js looks like this.
import adapter from '#sveltejs/adapter-node';
import preprocess from 'svelte-preprocess';
/** #type {import('#sveltejs/kit').Config} */
const config = {
preprocess: preprocess(),
kit: {
adapter: adapter({
out: 'dist'
}),
csrf: {
checkOrigin: false,
},
files: {
serviceWorker: 'src/firebase-messaging-sw.js'
}
},
};
export default config;
I am testing using vite build && vite preview with no luck. I feel like i'm missing a simple config to keep the file at the root of the project.

The solution I found was to use 'importScripts' a service worker helper I wasn't aware of.
importScripts('https://www.gstatic.com/firebasejs/9.10.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/9.10.0/firebase-messaging.js');

Related

Identifier 'module' has already been declared - amplify and nuxt 3

I am getting an error in nuxt3 then setting up this amplify plugin. I am trying to add auth to nuxt3 via plugins
plugins/amplify.js
import Amplify, {withSSRContext} from 'aws-amplify';
export default defineNuxtPlugin((ctx) => {
const awsConfig = {
Auth: {
region: "ap-south-1",
userPoolId: "ap-south-1_#########",
userPoolWebClientId: "#####################",
authenticationFlowType: "USER_SRP_AUTH",
},
};
Amplify.configure({ ...awsConfig, ssr: true });
if (process.server) {
const { Auth } = withSSRContext(ctx.req);
return {
provide: {
auth: Auth,
},
};
}
return {
provide: {
auth: Auth,
},
};
}
[nuxt] [request error] Identifier 'module' has already been declared
at Loader.moduleStrategy (internal/modules/esm/translators.js:145:18)
at async link (internal/modules/esm/module_job.js:67:21)
Does anyone know what's going on?
Been facing this myself... I don't think its a nuxt problem but rather Vite.
I gave up on running the app on dev mode and just resorted to building the app and launching it. Also, in order to use aws-amplify with vite you need to apply some workarounds:
https://ui.docs.amplify.aws/vue/getting-started/troubleshooting
For the window statement (which only makes sense on the browser) you'll need to wrap that with an if statement. Added this to my plugin file
if (process.client) {
window.global = window;
var exports = {};
}
This will let you build the project and run it with npm run build . Far from ideal but unless someone knows how to fix that issue with dev in vite...
BTW, you can also just switch to webpack builder on nuxt settings and the issue goes away.
// https://v3.nuxtjs.org/api/configuration/nuxt.config
export default defineNuxtConfig({
builder: "webpack"
});
I think this might be a problem with auto imports of nuxt.
I added a ~/composables/useBucket.ts file which I used in ~/api. Same error started popping up the next day. After I moved ~/composables/useBucket.ts to ~/composablesServer/useBucket.ts issue disappeared.

Next js in subfolder /blog change index.js file for example to _blog_index.js?

in subfolder /blog can i change index.js file for example to _blog_index.js and it will be read as index.js?
each subfolder has index.js file and sometime is difficult to read in code editor, when i have many subfolders and many tabs open.
Thank u
This is possible when using rewrites() in next.config.js:
const nextConfig = {
async rewrites() {
return [
{
source: "/blog",
destination: "/blog/_blog_index",
},
];
},
};
module.exports = nextConfig;
However, keep in mind that rewrites() won't be supported if you're planning to export your app to static HTML because it requires a Node.js server.

Next.js returns 500: internal server error in Production

Created a next.js full stack application. After production build when I run next start it returns 500 : internal server. I'm using environment varibles for hitting api.
env.development file
BASE_URL=http://localhost:3000
It was working fine in development
service.ts
import axios from 'axios';
const axiosDefaultConfig = {
baseURL: process.env.BASE_URL, // is this line reason for error?
headers: {
'Access-Control-Allow-Origin': '*'
}
};
const axio = axios.create(axiosDefaultConfig);
export class Steam {
static getGames = async () => {
return await axio.get('/api/getAppList');
};
}
Do you have a next.config.js file?
To add runtime configuration to your app open next.config.js and add the publicRuntimeConfig and serverRuntimeConfig configs:
module.exports = {
serverRuntimeConfig: {
// Will only be available on the server side
mySecret: 'secret',
secondSecret: process.env.SECOND_SECRET, // Pass through env variables
},
publicRuntimeConfig: {
// Will be available on both server and client
staticFolder: '/static',
},
}
To get access to the runtime configs in your app use next/config, like so:
import getConfig from 'next/config'
// Only holds serverRuntimeConfig and publicRuntimeConfig
const { serverRuntimeConfig, publicRuntimeConfig } = getConfig()
// Will only be available on the server-side
console.log(serverRuntimeConfig.mySecret)
// Will be available on both server-side and client-side
console.log(publicRuntimeConfig.staticFolder)
function MyImage() {
return (
<div>
<img src={`${publicRuntimeConfig.staticFolder}/logo.png`} alt="logo" />
</div>
)
}
export default MyImage
I hope this helps.
I dont think you have setup env.
You need to configure it for it to work. Try it without it and it should work fine!

How to use TS Path Mapping with Firebase Cloud Functions

How do I use TS Path Mapping with Firebase Cloud Functions?
I tried without success:
"baseUrl": ".",
"paths": {
"#custom-path/*": ["src/utils/*"],
"#other-path/*": ["../other/path/*"]
}
Finally I was able to do this with module-alias NPM package.
Install it as non-dev dependency: yarn add module-alias #types/module-alias
Create a file fixTsPaths.ts or whatever with content like this:
import * as ModuleAlias from 'module-alias';
ModuleAlias.addAliases({
'common': __dirname + '/../../../common',
});
Here's the trick about the path /../../../common: in my case this folder is outside functions, and Typescript replicates folders structure during the build, so that's could be the reason why https://github.com/dividab/tsconfig-paths was not working out of the box. So in every case one needs to check this path and find appropriate '..' count :)
And finally import this file in your index.ts at the very top:
import './fixTsPaths';
Hope this helps!
It's 2022 and the neatest way to do this is to use tsc-alias.
On tsconfig.json, add baseUrl and add your paths under compilerOptions. Something like:
{
"compilerOptions": {
...
"baseUrl": "./src",
"paths": {
"#constants/*": ["api/constants/*"],
"#interfaces/*": ["api/interfaces/*"],
"#middlewares/*": ["api/middlewares/*"],
"#modules/*": ["api/modules/*"],
"#services/*": ["api/services/*"]
},
...
}
Then, change your serve and build scripts, under package.json. Like:
...
"scripts": {
"build": "tsc && tsc-alias",
"build:watch": "concurrently \"tsc -w\" \"tsc-alias -w\"",
"serve": "concurrently --kill-others \"firebase emulators:start --only functions\" \"npm run build:watch\"",
...
},
...
☝️ here I'm using concurrently, but feel free to use whatever you like.
And that's it. You can now import stuff using your defined paths, like:
import { messages } from '#constants/responses'
import CandidatesService from '#modules/candidates/candidates.service'
import { IModule } from '#interfaces/module.interface'
etc...
The problem is the rule no-implicit-dependencies: true on the tslint.json. You can pass additional params to whitelist your custom paths:
"no-implicit-dependencies": [true, ["#custom-path", "#other-path"]],
for anyone who still struggles with this issue, but the below code at the top of the entry point file (main.ts).
don't forget to adjust the tsconfig.json file path if it is not in the default location
const tsConfig = require('../tsconfig.json');
const tsConfigPaths = require('tsconfig-paths');
tsConfigPaths.register({
baseUrl: __dirname,
paths: tsConfig.compilerOptions.paths,
});
I was able to do this with #zerollup/ts-transform-paths NPM package.
Install #zerollup/ts-transform-paths as dev dependency: yarn add -D #zerollup/ts-transform-paths
Setup following config of webpack + ts-loader.
const tsTransformPaths = require('#zerollup/ts-transform-paths');
module.exports = {
... // other config
module: {
rules: [
{
test: /\.(ts|tsx)$/,
loader: 'ts-loader',
options: {
getCustomTransformers: (program) => {
const transformer = tsTransformPaths(program);
return {
before: [transformer.before], // for updating paths in generated code
afterDeclarations: [transformer.afterDeclarations] // for updating paths in declaration files
};
}
}
}
]
}
};
See more in detail: https://github.com/zerkalica/zerollup/tree/5aee60287647350215c81d0b2da5a30717d9dccb/packages/ts-transform-paths

HMR in asp.net core with React

I started my project using .net core cli.
dotnet new react -o my app
and for development, I changed my env var
export ASPNETCORE_Environment=Development
I am not very comfortable with Typescript so, I prefer use .jsx files and babel, so I decided to change my webpack.config.js. In module rules, I added:
const BABEL_LOADER_PLUGINS = [
require.resolve("babel-plugin-transform-class-properties"),
require.resolve("babel-plugin-transform-object-rest-spread"),
require.resolve("babel-plugin-transform-regenerator")
];
/*...webpack config code ... */
{
test: /\.jsx$/,
exclude: /node_modules/,
use: [
{
loader: "babel-loader",
options: {
presets: ["env", "react"],
plugins: BABEL_LOADER_PLUGINS
}
}
]
}
I did my new components with .jsx extensions and it works. So my next step is to do HMR work.
In my Startup.cs:
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
{
HotModuleReplacement = true
});
}
In client at root component, using react-hot-loader':
let HotApp;
if (__CONFIGS__.isDevServer) {
const { hot } = require('react-hot-loader');
HotApp = hot(module)(App);
} else {
HotApp = App;
}
const Root = (
<Provider store={store}>
<BrowserRouter>
<HotApp />
</BrowserRouter>
</Provider>
);
hydrate(Root, document.getElementById('react-app'));
And this sometimes works. In the console, I can see [HMR] connected and updates. If I stop the process, it is possible that console shows [HMR] connected but if I do some changes in a component nothing happens. I don't know why sometimes works well.
We can use Create React App Configuration Override (#craco/craco) along with craco-plugin-react-hot-reload CRACO plugin to add HMR without ejecting the CRA application.
Install #craco/craco by following the installation guide
Install craco-plugin-react-hot-reload
npm i -D craco-plugin-react-hot-reload
Add craco-plugin-react-hot-reload into craco.config.js
const reactHotReloadPlugin = require('craco-plugin-react-hot-reload');
module.exports = {
plugins: [{
plugin: reactHotReloadPlugin
}],
webpack: [...]
}
Install #hot-loader/react-dom
npm i #hot-loader/react-dom
Mark your App component as hot-exported (into ClientApp\src\App.js)
import { hot } from 'react-hot-loader/root';
function App() {...}
export default hot(App);
Now HMR will work properly when we start the project using dotnet run.
Tested (on May 2020) using React 16.13.1. We must use the same major and minor versions for react, react-dom and #hot-loader/react-dom (16.13.x).

Resources