Hendrik Jan
Hendrik Jan
NNuxt
Created by Hendrik Jan on 8/15/2024 in #❓・help
Auto-import of /utils not working in VS-Code in template block
Even though my application builds and works fine, the auto-import of my function t() doesn't get recognized inside the <template>. The function is defined like this:
// /utils/translate.ts

/* some code left out */

export function t(key:string): string | null {
const lang = userData.value?.account?.language;
const translations = (lang == 'nl' ? nl : en);

if (!(key in translations)) {
console.warn('Translate key not found', key);
return null;
}

return translations[key];
}
// /utils/translate.ts

/* some code left out */

export function t(key:string): string | null {
const lang = userData.value?.account?.language;
const translations = (lang == 'nl' ? nl : en);

if (!(key in translations)) {
console.warn('Translate key not found', key);
return null;
}

return translations[key];
}
Inside the <script setup lang="ts"> block the auto-import works, but in the <template> block it doesn't. If I add import { t } from '~/utils/translate.ts' to the script it starts working in the template, but that would defy the usefullness of auto-imports.
<v-alert type="info">
{{ t('report_info_alert_1') }}
</v-alert>
<v-alert type="info">
{{ t('report_info_alert_1') }}
</v-alert>
Gives me the error:
Property 't' does not exist on type 'CreateComponentPublicInstance<Readonly<ExtractPropTypes<{}>>, { result: typeof result; totalCount: typeof totalCount; yearName: typeof yearName; error: typeof error; info: typeof info; ... 8 more ...; downloadExcel: typeof downloadExcel; }, ... 17 more ..., {}>'.ts-plugin(2339)
Property 't' does not exist on type 'CreateComponentPublicInstance<Readonly<ExtractPropTypes<{}>>, { result: typeof result; totalCount: typeof totalCount; yearName: typeof yearName; error: typeof error; info: typeof info; ... 8 more ...; downloadExcel: typeof downloadExcel; }, ... 17 more ..., {}>'.ts-plugin(2339)
Does anyone know how to get this working?
14 replies
NNuxt
Created by Hendrik Jan on 7/30/2024 in #❓・help
Can you extend H3EventContext?
I'm trying to type my context correctly so it can be used inside defineEventHandler() like this:
// file: /server/api/somefile.ts
export default defineEventHandler(async function(event) {
const context = event.context as Context;
...
})
// file: /server/api/somefile.ts
export default defineEventHandler(async function(event) {
const context = event.context as Context;
...
})
I'm trying to extend H3EventContext like this:
// file: /server/graphql/context.ts
export default class Context extends H3EventContext {
constructor(event: H3Event) {
this.user = event.context.user
}

user: any
}
// file: /server/graphql/context.ts
export default class Context extends H3EventContext {
constructor(event: H3Event) {
this.user = event.context.user
}

user: any
}
However, the type H3EventContext seems not to exist anywhere (import { H3EventHandler } from 'h3' doesn't work). Now, I found this issue that seems to be solved: https://github.com/unjs/h3/issues/122, but I don't understand how this works at all. I've tried to add this to /server/graphql/context.ts:
import {type NodeIncomingMessage, type NodeServerResponse, type H3Event} from 'h3'
declare module 'h3' {
interface CompatibilityEvent {
'__is_event__': true;
event: H3Event;
req: NodeIncomingMessage;
res: NodeServerResponse;
context: Context;
}
}
import {type NodeIncomingMessage, type NodeServerResponse, type H3Event} from 'h3'
declare module 'h3' {
interface CompatibilityEvent {
'__is_event__': true;
event: H3Event;
req: NodeIncomingMessage;
res: NodeServerResponse;
context: Context;
}
}
But this does not seem to fix anything.
4 replies
NNuxt
Created by Hendrik Jan on 7/2/2024 in #❓・help
Error "currentRenderingInstance is null" since upgrade of Nuxt
No description
5 replies
NNuxt
Created by Hendrik Jan on 6/24/2024 in #❓・help
How can I import a markdown file from /assets?
I've got a markdown file named "CHANGELOG.md" in my /assets folder that I want to import using typescript. * I added declare module "*.md"; to global.d.ts so Typescript will accept it in imports. * I've added import changelog from '~/assets/CHANGELOG.md'; to my file /pages/changelog.vue. * I've added vite: { assetsInclude: ['**/*.md'] } to my nuxt.config.js. This gives me the following error: Loading module from “https://tapp.docker.dev/_nuxt/assets/CHANGELOG.md?import” was blocked because of a disallowed MIME type (“text/html”) I also tried to get this working using CodeSandbox or Stackblitz, but they fail already when I add the change to nuxt.config.js: https://stackblitz.com/edit/github-zjjjbk?file=nuxt.config.ts How can I use .md files from my assets folder?
1 replies
NNuxt
Created by Hendrik Jan on 6/3/2024 in #❓・help
What path to use, to read a file from public folder?
The "dev" public folder is in another location than the "build" public folder. Using filesystem tools, how can you access these files in a way that works both in "dev" and in "prod"? I currently use this:
const isBuild = import.meta.url.includes('.output');
const staticPath = isBuild ? '../public' : '../../static';

legalFilePath = decodeURI(
new URL(
staticPath + '/legaltexts/' + v.AppointmentPosition.Appointment.legal_filename,
import.meta.url
).pathname
);

const fileFound = existsSync(legalFilePath);
const isBuild = import.meta.url.includes('.output');
const staticPath = isBuild ? '../public' : '../../static';

legalFilePath = decodeURI(
new URL(
staticPath + '/legaltexts/' + v.AppointmentPosition.Appointment.legal_filename,
import.meta.url
).pathname
);

const fileFound = existsSync(legalFilePath);
In nuxt.config.js we use the legacy "static" folder instead of "public" for historical reasons:
dir: {
public: 'static'
},
dir: {
public: 'static'
},
This does work, but it feels like a hack. Is there a clean way to generate a file path to the public folder that works both in "dev" and in "build"?
1 replies
NNuxt
Created by Hendrik Jan on 5/27/2024 in #❓・help
How to configure "~" alias when working with Docker?
No description
3 replies
NNuxt
Created by Hendrik Jan on 4/4/2024 in #❓・help
Way to catch errors in all composables?
Hi people, Is there a way to catch errors in any of your composables (client side)? I know that I can use <NuxtErrorBoundary> to catch errors in any component, but this does not catch errors in a composable. I also tried nuxtApp.hook('vue:error', ... in a plugin, which does catch some errors, but not in composables.
1 replies
NNuxt
Created by Hendrik Jan on 4/2/2024 in #❓・help
Getting error "Component is already mounted" when using "useFetch()" and changing route.
I am getting the error in my console:
[nuxt] [useFetch] Component is already mounted, please use $fetch instead.
[nuxt] [useFetch] Component is already mounted, please use $fetch instead.
This is when using multiple useFetch() in a composable and then navigating to another route. A reproduction can be found here: https://stackblitz.com/edit/github-o9ivmk-bcdf3h?file=layouts%2Fdefault.vue I'm quite sure it has to do with the composable useTwoStepFetch() but unsure how to solve. I cannot change useFetch() to $fetch, because I want the call to be deduped. Any ideas?
1 replies
NNuxt
Created by Hendrik Jan on 3/31/2024 in #❓・help
Can you use useFetch twice in one composable, once on server, once in client?
I am trying to use useFetch() once on the server and a second time in the client, in one composable. So far I have not been able to get this to work. A reproduction of my attempt can be found here: https://stackblitz.com/edit/github-o9ivmk?file=composables%2FuseTwoStepFetch.ts It is the second useFetch() with server:false that I cannot get to return something -- it always returns null. Is there a way to get this working? An example somewhere? The composable looks like this:
// Simplified example.
// Fetch data in two steps:
// 1. Quickly get a small number of records (3)
// 2. Get all the rest of the data
export async function useTwoStepFetch() {
const nuxtApp = useNuxtApp();
const result = ref([] as any[]);

// get the first 3 records
// use useFetch() so this call can be done on the server
const body1 = { take: 3 };
await nuxtApp.runWithContext(async () => {
const { data }: any = await useFetch('/api/hello', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: body1,
watch: false,
server: true,
lazy: false,
});

// Put data in the result
console.log('data.value (1)', data.value);
result.value = data.value;
});

// get the rest of the data
// ** HERE I WANT TO BE SURE THAT IT RUNS ONLY ON CLIENT **
const body2 = { skip: 3 };
// ** NO AWAIT BECAUSE WE WANT TO RETURN THE RESULT BEFORE THE CALL FINISHED **
nuxtApp.runWithContext(async () => {
const { data }: any = await useFetch('/api/hello', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: body2,
watch: false,
/* server:true, lazy:false works, but that is not what I want */
server: false,
lazy: true,
});

console.log('data.value (2)', data.value);
result.value.splice(result.value.length, 0, ...(data.value || []));
});

return result;
}
// Simplified example.
// Fetch data in two steps:
// 1. Quickly get a small number of records (3)
// 2. Get all the rest of the data
export async function useTwoStepFetch() {
const nuxtApp = useNuxtApp();
const result = ref([] as any[]);

// get the first 3 records
// use useFetch() so this call can be done on the server
const body1 = { take: 3 };
await nuxtApp.runWithContext(async () => {
const { data }: any = await useFetch('/api/hello', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: body1,
watch: false,
server: true,
lazy: false,
});

// Put data in the result
console.log('data.value (1)', data.value);
result.value = data.value;
});

// get the rest of the data
// ** HERE I WANT TO BE SURE THAT IT RUNS ONLY ON CLIENT **
const body2 = { skip: 3 };
// ** NO AWAIT BECAUSE WE WANT TO RETURN THE RESULT BEFORE THE CALL FINISHED **
nuxtApp.runWithContext(async () => {
const { data }: any = await useFetch('/api/hello', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: body2,
watch: false,
/* server:true, lazy:false works, but that is not what I want */
server: false,
lazy: true,
});

console.log('data.value (2)', data.value);
result.value.splice(result.value.length, 0, ...(data.value || []));
});

return result;
}
15 replies
NNuxt
Created by Hendrik Jan on 2/14/2024 in #❓・help
Using Nuxt3 behind Apache proxy?
Hi, has anyone experience on getting Nuxt to work behind an Apache proxy? I've tried anything I can think of but HMR keeps giving errors in my console. Part of my Virtualhost definition looks like this:
<Location ~ ".*">
# .* is a wildcard for any location
ProxyPreserveHost On
ProxyPass http://tapp_nodejs.docker.dev:3000
ProxyPassReverse http://tapp_nodejs.docker.dev:3000
</Location>
<Location ~ "/_nuxt/ws">
RewriteEngine on
RewriteCond ${HTTP:Upgrade} websocket [NC]
RewriteCond ${HTTP:Connection} upgrade [NC]
RewriteRule .* "wss://tapp_nodejs.docker.dev:24678/$1" [P,L]

ProxyPreserveHost On
ProxyPass https://tapp_nodejs.docker.dev:24678
ProxyPassReverse https://tapp_nodejs.docker.dev:24678
</Location>
<Location ~ ".*">
# .* is a wildcard for any location
ProxyPreserveHost On
ProxyPass http://tapp_nodejs.docker.dev:3000
ProxyPassReverse http://tapp_nodejs.docker.dev:3000
</Location>
<Location ~ "/_nuxt/ws">
RewriteEngine on
RewriteCond ${HTTP:Upgrade} websocket [NC]
RewriteCond ${HTTP:Connection} upgrade [NC]
RewriteRule .* "wss://tapp_nodejs.docker.dev:24678/$1" [P,L]

ProxyPreserveHost On
ProxyPass https://tapp_nodejs.docker.dev:24678
ProxyPassReverse https://tapp_nodejs.docker.dev:24678
</Location>
And to handle wss on with Nuxt I have this in nuxt.config:
vite: {
server: {
hmr: {
path: "ws",
port: 24678,
server: {
https: {
key: readFileSync('docker/certificates/docker.dev.key'),
cert: readFileSync('docker/certificates/docker.dev.crt'),
enableTrace: true
}
}
}
}
},
vite: {
server: {
hmr: {
path: "ws",
port: 24678,
server: {
https: {
key: readFileSync('docker/certificates/docker.dev.key'),
cert: readFileSync('docker/certificates/docker.dev.crt'),
enableTrace: true
}
}
}
}
},
Apache responds with: https: attempt to connect to 172.19.0.9:24678 (tapp_nodejs.docker.dev:24678) failed
8 replies