Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lazy load files not working #2192

Closed
userquin opened this issue Jul 2, 2023 · 21 comments · Fixed by #2193 or #2294
Closed

lazy load files not working #2192

userquin opened this issue Jul 2, 2023 · 21 comments · Fixed by #2193 or #2294

Comments

@userquin
Copy link
Collaborator

userquin commented Jul 2, 2023

Environment

npx nuxi info
Nuxi 3.6.1                                                                                                                                                                18:48:21
                                                                                                                                                                          18:48:21
RootDir: D:/work/projects/userquin/GitHub/userquin/vuetify-nuxt-module-main                                                                                               18:48:21
Nuxt project info:                                                                                                                                                        18:48:21

------------------------------
- Operating System: Windows_NT
- Node Version:     v18.16.0
- Nuxt Version:     3.6.1
- Nitro Version:    2.5.2
- Package Manager:  pnpm@8.6.5
- Builder:          vite
- User Config:      -
- Runtime Modules:  -
- Build Modules:    -
------------------------------

Reproduction

Fork https://github.com/userquin/vuetify-nuxt-module/ and then chekout feat-add-i18n-support branch:
https://github.com/userquin/vuetify-nuxt-module/tree/userquin/feat-add-i18n-support (I'm working in the PR to add i18n support to Vuetify 3)

Run pnpm install, and then you can run:

  • nr dev:prepare && nr dev: for single json file per locale
  • nr dev:prepare:multiple-json && nr dev:multiple-json: for multiple json files per locale

Describe the bug

Cannot load lazy translation files other than the default/fallback locale.

Additional context

I'm preparing a PR to fix the error, PR in a few minutes.

Logs

No response

@kazupon kazupon added v8 ❗ p4-important Priority 4: bugs that violate documented behavior, or significantly impact perf locale labels Jul 3, 2023
@agracia-foticos
Copy link

with new beta 13 not runs yet :(

@kazupon kazupon reopened this Jul 10, 2023
@kazupon
Copy link
Collaborator

kazupon commented Jul 10, 2023

I've reverted #2193

@userquin
I’m sorry for the issue you are going through.
Could you please give a reproduction again?

@userquin
Copy link
Collaborator Author

@kazupon you can clone the repo, remove the pnpm patch and update manually the i18 module: remove this 3 lines https://github.com/userquin/vuetify-nuxt-module/blob/main/playground/pages/index.vue#L61-L63

@userquin
Copy link
Collaborator Author

userquin commented Jul 15, 2023

@kazupon it seems we've a problem using i18n to get old locale when calling loadAndSetLocale in the locale-changing middleware, the old locale always gets the new locale.

I guess we need to calculate the old and the new locales from the to and from routes in the middleware; if I enable alwaysRedirect: true and redirectOn: 'all' there is no way to switch the locale: the call to detectLocale in the middleware will always return the first lang matched in the browser.

I'm using a v-select component to swtich the locale in my vuetify nuxt playground (a selector) and I need to use this logic to switch the locale:

    const route = useRoute()
    const router = useRouter()
    const switchLocalePath = useSwitchLocalePath({ route, router, i18n })
    watch(current, (l) => {
      router.push({ path: switchLocalePath(l) })
    }, { immediate: true })

If I hack the old locale in the browser dev tools inside the loadAndSetLocale, it is working, the new locale json file is there.

@userquin
Copy link
Collaborator Author

userquin commented Jul 15, 2023

This is the i18n configuration:

i18n: {
    locales: availableLocales,
    lazy: true,
    strategy: 'prefix',
    detectBrowserLanguage: {
      fallbackLocale: 'en-US',
      useCookie: false,
      // alwaysRedirect: true,
      // redirectOn: 'all',
    },
    langDir,
    defaultLocale: 'en-US',
    // types: 'composition',
    // pages: undefined,
    dynamicRouteParams: true,
    skipSettingLocaleOnNavigate: false,
    debug: true,
    vueI18n: './config/i18n.config.ts',
  },

imagen

@userquin
Copy link
Collaborator Author

userquin commented Jul 15, 2023

I'll check it in the playground here...

in the playground seems to be working, but getting missing japanese entry:

imagen

imagen

@userquin
Copy link
Collaborator Author

about the null and missing entries, I can see this weird encodings using this middleware:

nuxt.hook('vite:serverCreated', viteServer => {
      viteServer.middlewares.stack.unshift({
        route: '',
        // @ts-expect-error just ignore
        handle: (req, res, next) => {
          const url = req.url
          let idx = url?.indexOf('@nuxtjs/i18n/')
          if (idx > -1) {
            console.log('url', { url, idx })
          }
          next()
        }
      })
    })

imagen

Copy link
Collaborator

kazupon commented Jul 16, 2023

@userquin

Thank you for your working which find out cause!
I’ve also confirmed your repo.

The reason for the lazy loading not working is that the oldLocale obtained with getLocale(i18n) has already changed at the time of loadAndSetLocale.
getLocale(i18n) gets the locale from the vue-i18n instance.

If we are using the no_prefix strategy, you must change the locale manually with setLocale.

I tried using setLocale in your reproduction repo, but the value retrieved with getLocale(i18n) had already changed.
This is not expected behavior for a nuxt i18n module.

I seem that the useLocale behavior provided by vuetify is affecting the vue-i18n side.
I think we need to understand vuetify's i18n behavior in order for it to work properly with the vuetify nuxt module.

@kazupon kazupon added upstream issue and removed locale labels Jul 16, 2023 — with Volta.net
@userquin
Copy link
Collaborator Author

So, we cannot use the locale as model from useI18n. I also test it using prefix, and prefix except default.

I will change the logic and update the documentation.

@userquin
Copy link
Collaborator Author

I seem that the useLocale behavior provided by vuetify is affecting the vue-i18n side.
I think we need to understand vuetify's i18n behavior in order for it to work properly with the vuetify nuxt module.

I have a custom module for it, check src/runtime/plugins/i18n.ts module, current vuetify i18n integration is broken since it is using i18n.global and cannot be used with i18n nuxt module.

You can test my repo exposing a new ref and changing the value (also add the import import type { Locale } from 'vue-i18n' ):

// src/runtime/plugins/i18n.ts
  const messages = i18n.messages 
// add this in L22
  
  const currentLocale = ref<Locale>(current.value)
  const route = useRoute()
  const router = useRouter()
  const switchLocalePath = useSwitchLocalePath({ route, router, i18n })

  watch(currentLocale, (l) => {
    // i18n.setLocale(locale)
    router.push({ path: switchLocalePath(l) })
  }, { immediate: true })

then replace current with currentLocale in the adapter:

vuetifyOptions.locale.adapter = {
    name: 'nuxt-vue-i18n',
    current: currentLocale, // <=== we can use it in the index.vue page
    fallback,
    messages,
    t: (key, ...params) => i18n.t(key, params),
    n: i18n.n,
    provide: createProvideFunction({ current, fallback, messages }),
  }
// src/pages/index.vue
  <v-select
      v-model="current" // <=== change the locale to use it from `useLocale`
      :items="locales"
      item-title="name"
      item-value="code"
      outlined
    />

@userquin
Copy link
Collaborator Author

@kazupon it seems to be working using edge version in my local, I'll send an update to my vuetify repo: added a few changes to avoid changing i18n local directly using setLocale and listening to changes viai18n:localeSwitched hook.

Copy link
Collaborator

kazupon commented Jul 24, 2023

@userquin
Thanks for your sharing.
I hope your nuxt module works well :)

@sauravbv
Copy link

sauravbv commented Jul 27, 2023

Following, have the same issue

All locale files are loading even though the lazy option is set true. Below is my i18n config.
Using version 8.0.0-beta.13

i18n: {
    vueI18n: 'i18n.config.ts',
    strategy: 'no_prefix',
    detectBrowserLanguage: {
      useCookie: false
    },
    locales: [
      {
        code: 'da',
        file: 'da.json'
      },
      {
        code: 'en',
        file: 'en_US.json'
      },
      .
      .
 // some more locales all in .json files
    ],
    lazy: true,
    langDir: 'locales',
    defaultLocale: 'en',
    experimental: {
      jsTsFormatResource: true
    }
  }
image

@kazupon kazupon removed the ❗ p4-important Priority 4: bugs that violate documented behavior, or significantly impact perf label Jul 30, 2023 — with Volta.net
Copy link
Collaborator

kazupon commented Jul 30, 2023

@sauravbv
It has fixed nuxt i18n edge channel latest version.
You can try to install 8.0.0-beta.13-28175294.3a94c60

@BobbieGoede
Copy link
Collaborator

This issue is still present in builds, it looks like lazy loaded locales are all loaded on page load as prefetch scripts (this can be confirmed by building playground and checking page source).

I think the discussion in issue #1875 is on the right track, and nuxt-contrib/vue-bundle-renderer#50 could make it possible to prevent prefetching/preloading, but I think Nuxt needs to include this change first.

In the meantime I will look into making the lazy loading tests more robusts, right now they only test whether lazy loaded files are loaded, not whether they are loaded on demand.

@sauravbv
Copy link

sauravbv commented Aug 3, 2023

Yes, recently tried with edge versions and the latest 8.0.0-rc-2 have the same issue.

I am trying a lot to optimise page load performance. Translations are being used only in some components and these components are not being used always as my page is dynamic. Is there a way to load the i18n module only when that component is used? Right now I have added nuxtjs/i18n part of modules in nuxt.config and it's contributing to the size of the entry file, trying to reduce the entry.js file size. Any suggestion/help is appreciated.
Thank you :)

Copy link
Collaborator

kazupon commented Aug 9, 2023

I’m back from short vacation.

nuxt-contrib/vue-bundle-renderer#50 could make it possible to prevent prefetching/preloading, but I think Nuxt needs to include this change first.

I checked nuxt v3.7 PR.
As far as I can see, that PR does not seem to included the vue-bundle-renderer resolved issue. /cc @danielroe
nuxt/nuxt#22222

@danielroe
Copy link
Contributor

Have you tested with the edge channel? We should have updated to v2 of vue-bundle-renderer there. You can hook into the build:manifest hook and add .prefetch = false to the manifest to disable resource hints being rendered in the HTML.

(It's also possible that vite injects prefetch links on the client-side in some situations.)

Copy link
Collaborator

kazupon commented Aug 9, 2023

Thank you for your mention about it.

We have already PR that can confirm it.
#2294

@BobbieGoede
Could you update #2294 please?

@BobbieGoede
Copy link
Collaborator

@kazupon @danielroe
Can confirm that the Nuxt edge channel includes vue-bundle-renderer: 2.0.0, updated #2294.

After installing the edge version I did run into a different issue and had to add an override for h3 to set it to 1.8.0-rc.3 as it kept throwing errors, I think this may be related to vitest or the test-utils, not sure.

@danielroe
Copy link
Contributor

@BobbieGoede Yes, this is the case at the moment as edge channel currently relies on prerelease versions of both nitro/h3. Your workaround is correct, and won't be needed once next nitro version is released.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

6 participants