Code Monkey home page Code Monkey logo

astro-i18next's People

Contributors

alexandre-fernandez avatar anomander43 avatar aquaminer avatar blarfoon avatar cauboy avatar dallyh avatar dschoeni avatar florian-lefebvre avatar jcdogo avatar jkjustjoshing avatar mellkam avatar preya avatar semantic-release-bot avatar yassinedoghri avatar zerdox-x avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

astro-i18next's Issues

1.0.0 beta 14 breaks loadPath

After this commit all my keys returns default untranslated string.

The temporary workaround that works for me is this snippet bellow:

/** @type {import('astro-i18next').AstroI18nextConfig} */
export default {
  ...
  i18nextServer: {
    backend: {
      loadPath: "./public/locales/{{lng}}/{{ns}}.json",
    },
  },
};

My config file (works fine in beta 13, but not in 14)

/** @type {import('astro-i18next').AstroI18nextConfig} */
export default {
  namespaces: ["common", "footer", "nav"],
  defaultNamespace: "common",
  defaultLocale: "en",
  locales: ["en", "pt", "vi"],
  showDefaultLocale: true
};

My page

Path: src/pages/[lang]/index.astro

πŸ’‘ The reason I made a path that way is precisely because it is not possible to use the generate command with showDefaultLocale set to true. It just doesn't extract anything, so the alternative was to create a folder with lang as param and manually set it inside the page (since this is a small project with only one page anyway)

---
import i18n from "i18next";

import MainLayout from "@layouts/MainLayout.astro";

// ....

export function getStaticPaths() {
  return [{ params: { lang: "en" } }, { params: { lang: "pt" } }, { params: { lang: "vi" } }];
}

const { lang } = Astro.params;
i18n.changeLanguage(lang as string);
---

<MainLayout>
  <p>{i18n.t('example')}</p>
  <!-- all contents -->
</MainLayout>

πŸ“œ Plans for v1.0.0 release

astro-i18next is currently in beta. Before releasing v1.0.0, some things need to be worked out, mainly to improve DX.

Developers should be able to translate their Astro website / app as fast as possible --> reduce manual tasks to setup / use the integration.

Roadmap:

  • add i18next plugins to config
    πŸ‘‰ removed in beta.13, astro-i18next takes care of the basic stuff (loading translation strings, locale detection, etc.)
    πŸ‘‰ added back in beta.14 (5ddb1c7)
  • npx astro-i18next generate: generate localized pages using command (based on config file) (#13)
  • Translate routes, possible thanks to @Alexandre-Fernandez !
    πŸ‘‰ Having routes.json files alongside pages would be best for i18n collaboration (#29)
  • #110
    ❌ MAYBE NO NEED: Probably by creating a Vite plugin and adding it to the astro:config:setup hook.
    πŸ‘‰ use astro's injectRoute function in the astro:config:setup to inject localized routes during build time. The generate CLI tool would most probably be discarded. pages folder wouldn't need to include localized pages anymore!
  • Test support for SSR
    βœ… Works with node adapter
    ❌ Doesn't work with Netlify yet: #26 - Reproduction
    πŸ‘‰ Missing support for Deno
  • Test client side i18n support
    βœ… Works with react
    πŸ‘‰ try out with other frontend frameworks
  • #108
  • npx astro-i18next init: automatic astro-i18next setup / config
  • Move the documentation from README.md to the website
  • Release v1.0.0 πŸš€

EDIT 2022-11-06: beta.13 is now out and I'm getting closer to a clean and simple API for everyone. Any feedback is welcome!

Build issues using the Deno adapter?

Hello, I am new to Astro and experiencing the following error trying to build my website using the Deno adapter for Astro. Is there any way I can fix the following issue?

$ npm run build
> @example/[email protected] build
> astro build

17:30:08 [build] output target: server
17:30:08 [build] deploy adapter: @astrojs/deno
17:30:08 [build] Collecting build info...
17:30:08 [build] Completed in 18ms.
17:30:08 [build] Building server entrypoints...
[commonjs--resolver] Cannot bundle Node.js built-in "fs" imported from "node_modules\i18next-fs-backend\esm\fs.cjs". Consider disabling ssr.noExternal or remove the built-in dependency.
file: F:/Programming/Astro/Projects/astragoWebsite/node_modules/i18next-fs-backend/esm/fs.cjs
 error   Cannot bundle Node.js built-in "fs" imported from "node_modules\i18next-fs-backend\esm\fs.cjs". Consider disabling ssr.noExternal or remove the built-in dependency.
  File:
    F:/Programming/Astro/Projects/astragoWebsite/node_modules/i18next-fs-backend/esm/fs.cjs
  Stacktrace:
Error: Cannot bundle Node.js built-in "fs" imported from "node_modules\i18next-fs-backend\esm\fs.cjs". Consider disabling ssr.noExternal or remove the built-in dependency.
    at error (file:///F:/Programming/Astro/Projects/astragoWebsite/node_modules/rollup/dist/es/shared/rollup.js:1858:30)
    at throwPluginError (file:///F:/Programming/Astro/Projects/astragoWebsite/node_modules/rollup/dist/es/shared/rollup.js:21781:12)
    at Object.error (file:///F:/Programming/Astro/Projects/astragoWebsite/node_modules/rollup/dist/es/shared/rollup.js:22503:20)
    at Object.resolveId (file:///F:/Programming/Astro/Projects/astragoWebsite/node_modules/vite/dist/node/chunks/dep-4da11a5e.js:34370:34)
    at Object.handler (file:///F:/Programming/Astro/Projects/astragoWebsite/node_modules/vite/dist/node/chunks/dep-4da11a5e.js:45996:19)
    at file:///F:/Programming/Astro/Projects/astragoWebsite/node_modules/rollup/dist/es/shared/rollup.js:22710:40```

how to add the lang folder to the baseLanguage.

Hi,
my current page structure is like this:

[lang]
 - about.astro
 - news.astro
 - contact.astro
 - index.astro
index.astro (homepage default lang or redirect to user locale)

So except for the homepage in baseLanguage I always add the [lang] to every URL.
How can I do this?

(in my setup the HeadHrefLangs & LanguageSelector won't work.)

I would like not to have a structure like this:

[lang]
 - about.astro
 - news.astro
 - contact.astro
 - index.astro
about.astro
news.astro
contact.astro
index.astro

Thanks!

How to generate mutilple languages pages when default language page files changed

I exec astro-generate when default language pages files changed, but astro-generate could emit the change of default languages pages files.
such as:

// package.json
"scripts": {
    "dev": "astro dev",
    "start": "astro dev",
    "build": "astro build",
    "preview": "astro preview",
    "astro": "astro",
    "gen:i18n": "astro-i18next generate"
  },
// genI18n.js
chokidar
  .watch(['src/pages/**/*', '!src/pages/en/**/*'])
  .on('all', (event, path) => {
    console.log(event, path, 'timeout gen i18n pages');
    execSync('npm run gen:i18n')
    // generate('', 'zh', 'en')
  });

Url generate with lastest / char

Url generates with / char and language selector doesn't find the page. If I remove / char, goes the page without any translation.

<select onchange="location = this.value;" class="form-select">
  <option value="/fr/index.html/" selected="true">
          πŸ‡«πŸ‡· FranΓ§ais
        </option><option value="/index.html/">
          πŸ‡ΊπŸ‡Έ English
        </option><option value="/de/index.html/">
          πŸ‡©πŸ‡ͺ Deutsch
        </option>
</select>

`<HeadHrefLangs />` doesn't respect the `routes` object and `showDefaultLocale`

When you have setup the routes object, which works just fine for localised links and paths, the head i18n components don't respect it. It even ignores the showDefaultLocale setting, as setting it false as is the default still adds a suffix of the language on the default locale.

In this basic example, on /it/notizie and /news it should show /news and /it/notizie as alternates, but instead shows:

  • on /news, /en/news and /it/news, missing the current completely and setting the alternate wrong.
  • on /it/notizie, /en/notizie and /it/notizie, missing only the alternate.

If I were to set showDefaultLocale to true, of course the currents are both corrects, but the alternates would be wrong.

https://stackblitz.com/edit/yassinedoghri-astro-i18next-issue-65

support react-i18next

Hi guys!
I can`t understand how to add react-i18next with your i18next configuration... It might be a stupid question, sorry)

Can't get i18next-browser-languageDetector plugin to work

For the past few days I've been trying to get this plugin to work: https://github.com/i18next/i18next-browser-languageDetector.

Everything I do fails, and the plugin doesn't actually do anything. I dug through it's source code and it uses simple methods to detect the language in the browser, for example by path (http://site.com/LANGUAGE): https://github.com/i18next/i18next-browser-languageDetector/blob/master/src/browserLookups/path.js, by navigator.language: https://github.com/i18next/i18next-browser-languageDetector/blob/master/src/browserLookups/navigator.js and such.

I have confirmed that the plugin actually loads, but simply doesn't do anything and I got stuck.

To my understanding i18next in astro-i18next gets loaded with page-ssr which from the Astro API page documentation says:

Imported as a separate module in the frontmatter of every Astro page component. Because this stage imports your script, the Astro global is not available and your script will only be run once when the import is first evaluated.

Does this actually mean, that all of the window objects are unavailable for the plugin , and that is why it doesn't work, or am I missing something?

Configured repo with this plugin is here.
From the i18next documentation, changeLanguage gets called on Layout.astro without lng:

Calling changeLanguage without lng uses the language detector to choose the language to set.

This may be not an issue with this plugin, but rather my misunderstading of it or of Astro.

Thanks!

astro-i18-next does not build with netlify edge-functions as it relies on internal node js APIs

Any pointers would be much appreciated. Keen to use edge functions if possible, or at least to understand the path down the line

[commonjs--resolver] Cannot bundle Node.js built-in "module" imported from "node_modules/astro-i18next/dist/index.js". Consider disabling ssr.noExternal or remove the built-in dependency.
 error   Cannot bundle Node.js built-in "module" imported from "node_modules/astro-i18next/dist/index.js". Consider disabling ssr.noExternal or remove the built-in dependency.
Error: Cannot bundle Node.js built-in "module" imported from "node_modules/astro-i18next/dist/index.js". Consider disabling ssr.noExternal or remove the built-in dependency.
    at error (file:///home/ninjaa/bp/agreeable-ascension/node_modules/rollup/dist/es/shared/rollup.js:1858:30)
    at throwPluginError (file:///home/ninjaa/bp/agreeable-ascension/node_modules/rollup/dist/es/shared/rollup.js:21587:12)
    at Object.error (file:///home/ninjaa/bp/agreeable-ascension/node_modules/rollup/dist/es/shared/rollup.js:22541:20)
    at Object.resolveId (file:///home/ninjaa/bp/agreeable-ascension/node_modules/vite/dist/node/chunks/dep-67e7f8ab.js:33611:34)
    at Object.handler (file:///home/ninjaa/bp/agreeable-ascension/node_modules/vite/dist/node/chunks/dep-67e7f8ab.js:45606:19)
    at file:///home/ninjaa/bp/agreeable-ascension/node_modules/rollup/dist/es/shared/rollup.js:22748:40

Found a relatable issue for astrojs/image
withastro/astro#5307

Error when using React but not using react-i18next

I have a project where I'm using React components, but I haven't installed/imported react-i18next. I updated astro-i18next and I'm getting an error that react-18next can't be resolved. But I'm not doing any translations in my React components and shouldn't need react-i18next installed. It was working fine on an earlier beta version.

Reproduction

https://stackblitz.com/edit/astro-i18next-react-error

Reproduction steps

  1. Install latest astro-i18next
  2. Install @astrojs/react, react, and react-dom
  3. Create a .jsx file and import it into an astro page file. Don't require any translations in the React file.
  4. Try starting dev server or running a build.

Expected - server starts/builds without errors
Current - error complaining that react-i18next isn't installed.

Cannot run astro-i18next on StackBlitz

I am receiving errors when trying to yarn run astro with astro-i18next attached.
As soon as I take out astro-i18next from astro.config.mjs integrations, everything works fine.

Stack Blitz Link

Error Message

image

astro.config.js

import { defineConfig } from 'astro/config';
import tailwind from '@astrojs/tailwind';
import sitemap from '@astrojs/sitemap';
import astroI18next from 'astro-i18next';

// https://astro.build/config
export default defineConfig({
  experimental: {
    integrations: true,
  },
  integrations: [tailwind(), sitemap(), astroI18next()],
}); 

astro-i18next.config.ts

/** @type {import('astro-i18next').AstroI18nextConfig} */
export default {
  defaultLanguage: 'en',
  supportedLanguages: ['en'],
  i18next: {
    // debug is convenient during development to check for missing keys
    debug: true,
    initImmediate: false,
    backend: {
      loadPath: './src/locales/{{lng}}.json',
    },
  },
  i18nextPlugins: { fsBackend: 'i18next-fs-backend' },
};

package.json

{
  "name": "@example/basics",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "dev": "astro dev",
    "start": "astro dev",
    "build": "astro build",
    "preview": "astro preview",
    "astro": "astro"
  },
  "devDependencies": {
    "@astrojs/sitemap": "^1.0.0",
    "@astrojs/tailwind": "^1.0.0",
    "astro": "^1.0.7",
    "astro-i18next": "^1.0.0-beta.4",
    "i18next-fs-backend": "^1.1.5"
  }
}

Error on generate, 1.0.0-beta.13

This is from Vercel, but the same error occurs on my machine.
Rolling back to 1.0.0-beta.12 fixes the issue. Astro is on 1.6.10.

πŸ§ͺ Localized .astro pages were generated successfully, it took 8ms!
--
11:15:24.568 | file:///vercel/path0/node_modules/astro-i18next/dist/cli/index.js:351
11:15:24.570 | `+e,vI=(e,i=1)=>(e.startsWith("./")&&(e=e.slice(2)),e.padStart(e.length+i*3,"../")),kU=e=>/((^_)\|(\/_))/.test(e),xI=e=>Kh.default.createSourceFile("x.ts",EU(e),Kh.default.ScriptTarget.Latest),CI=(e,i,u)=>{let _=Kh.default.transform(e,[mI],{locale:i,fileDepth:u});return Kh.default.createPrinter().printNode(Kh.default.EmitHint.Unspecified,_.transformed[0],e)},BC=(e,i=void 0,u=[])=>{let _=new hI.fdir().filter(y=>!kU(y)&&y.endsWith(".astro")).exclude(y=>u.includes(y)).withRelativePaths();return i?_.crawl(`${e}${DI.sep}${i}`).sync():_.crawl(e).sync()},TI=e=>{e.forEach(i=>{yI.default.ensureDirSync(DI.dirname(i.path)),TU.writeFileSync(i.path,i.source)})},EI=(e,i=null,u="",_={})=>{if(e=e.replace(/^\/+\|\/+$/g,""),u=u.replace(/\/+$/g,""),i===null)return`${u}/${e}`;e=e.replace(/.astro$/,"");let y=`/${i}/${e}`;return Object.prototype.hasOwnProperty.call(_,y)?`${u}${_[y]}.astro`:`${u}/${i}/${e}.astro`};var kI=(e,i,u,_=!1,y,m=e)=>{let w=process.hrtime(),q=_?BC(e,i,u):BC(e,void 0,u),x=[];return q.forEach(async function(D){let v=_?[e,i,D].join("/"):[e,D].join("/"),ie=AU.readFileSync(v).toString(),se=xI(ie);u.forEach(pe=>{let g=pe!==i,p=CI(se,pe,_?0:Number(g)),W=SI(ie,p),O=_?!0:g;x.push({path:EI(D,O?pe:void 0,m,y),source:W})})}),TI(x),{filesToGenerate:x,timeToProcess:process.hrtime(w)[1]/1e6}};import{pathToFileURL as PU}from"url";import GV,{t as KV}from"i18next";import{fileURLToPath as AI}from"url";import NI from"@proload/core";import NU from"@proload/plugin-tsm";var PI=async(e,i)=>{let u=AI(e),_;if(i){let y=/^\.*\//.test(i)?i:`./${i}`;_=AI(new URL(y,e))}return NI.use([NU]),await NI("astro-i18next",{mustExist:!1,cwd:u,filePath:_})};var II=async e=>{let{path:i,config:u}=e,_=await PI(PU(i),u);if(i&&!(_!=null&&_.value))throw new Error(`Could not find a config file at ${JSON.stringify(i)}. Does the file exist?`);return{...e,config:_==null?void 0:_.value}},wI=async e=>{let{path:i}=e;return{...e,path:i.endsWith("/")?i:i+"/"}};vN(Bx(process.argv)).usage("usage: $0 <command>").command("generate [path] [options]","generates localized Astro pages",e=>e.positional("path",{type:"string",description:"Path to the Astro project folder",default:"./"}).option("output",{alias:"o",type:"string",description:"Set the output of the generated pages if different from input"}),async e=>{e.verbose&&console.info(`Generating localized pages: ${e.config.locales}`);let i=e.path+"src/pages",u=Nx(e.config.routes),_=kI(i,e.config.defaultLocale,e.config.locales,e.config.showDefaultLocale,u,e.output);if(e.verbose){let y=_.filesToGenerate.map(m=>m.path);console.log(`
11:15:24.571 | Β 
11:15:24.571 | TypeError: Cannot read properties of undefined (reading 'forEach')
11:15:24.571 | at file:///vercel/path0/node_modules/astro-i18next/dist/cli/index.js:351:1111
11:15:24.572 | at Array.forEach (<anonymous>)
11:15:24.572 | at kI (file:///vercel/path0/node_modules/astro-i18next/dist/cli/index.js:351:998)
11:15:24.572 | at Object.handler (file:///vercel/path0/node_modules/astro-i18next/dist/cli/index.js:351:2411)
11:15:24.572 | at file:///vercel/path0/node_modules/astro-i18next/dist/cli/index.js:285:27978
11:15:24.572 | at Nv (file:///vercel/path0/node_modules/astro-i18next/dist/cli/index.js:285:24124)
11:15:24.572 | at zx.handleValidationAndGetResult (file:///vercel/path0/node_modules/astro-i18next/dist/cli/index.js:285:27960)
11:15:24.572 | at file:///vercel/path0/node_modules/astro-i18next/dist/cli/index.js:285:28532
11:15:24.592 | Error: Command "npx astro-i18next generate && npm run build" exited with 1

Repeat runs of `generate` create more nested folders due to incorrect isLocale check

There is the assumption that locale is 2 letter language and 2 letter region in CLI utils

However, language can be 3 letters, and language may be followed by script before region. See Unicode CLDR

Thus, locales such as yue-HK (3 letter language) and zh-Hans (script specified, no region) are not recognized by isLocale and these folders are treated as normal folders and localization logic is run on these files, creating a deeper nested structure on each run of generate. E.g. zh-Hans/zh-Hans, zh-Hans/yue-HK, yue-HK/yue-HK, yue-HK/zh-Hans.

Since isLocale is only used by getAstroPagesPath, and getAstroPagesPath is used only by generate, I would propose the problem be fixed by removing getAstroPagesPath and isLocale, and replacing the logic in generate to check locale against i18next.options.supportedLngs, like in localizePath

File routing based JSON localization

what if instead of just a en.json file, instead we could have an en folder, with multiple JSON files each mapping to a different page? This would improve the readability of the individual files

localizePath and ids

Hi, when using localizePath with and id in it (#contact for instance), it adds an / at the end. Here is a workaround I've made but not ideal:

return href.startsWith('#') ? href : localizePath(href)

Unexpected token 'export'

Hi everyone,
after updating to 1.0.0-beta.4 i've become the following error:

image

This is my config-file:
image

I hope someone can help πŸ™

i18next is undefined inside layout

I get this error inside my layout because it can't access the i18next variable. It would be really nice if I could automatically detect the locale in my layout because that's where I put my tag.

No keys were found

I have tried following the stackblitz example but I get an error referring to missing keys. The following is one of them:
WARNING(astro-i18next): missing translation key welcome.

astro-i18next.config.mjs

/** @type {import('astro-i18next').AstroI18nextConfig} */
export default {
  defaultLocale: "en",
  locales: ["en", "fr"],
  i18next: {
    // debug is convenient during development to check for missing keys
    debug: true,
    initImmediate: false,
    backend: {
      loadPath: './src/locales/{{lng}}.json',
    },
  },
  i18nextPlugins: { fsBackend: 'i18next-fs-backend' },
};

src/locales/en.json

{
    "pageTitle": "Welcome to Astro.",
    "welcome": "Welcome to <0>Astro</0>",
    "instructions": "Checkout the <0>src/pages</0> directory to get started.<1><2>Code Challenge:</2> Translate this page with your language of choice.",
    "cards": {
      "documentation": {
        "title": "Documentation",
        "body": "Learn how Astro works and explore the docs."
      },
      "integrations": {
        "title": "Integrations",
        "body": "Supercharge your projects with new frameworks and libraries."
      },
      "themes": {
        "title": "Themes",
        "body": "Explore a galaxy of community-built starter themes."
      },
      "chat": {
        "title": "Chat",
        "body": "Come and say hi to our amazing Discord community. ❀️"
      }
    }
}

Consider adding .gitattributes file with line ending set to LF

Hi again!

I was just trying to do some modifications on this repository, and when I spin up a docker all my files changed. It was because of the line endings, which get converted on git clone. I had this option set in my global git config core.autocrlf=true which basically converts all line endings to CRLF on Windows machines. I forgot about this when I was setting up my Git, and I believe that I'm not the only one that has this setting set to "true". The .gitattribute file should help people like me (who forgot things :)).

This should be enough I believe:
* text=auto eol=lf *.{cmd,[cC][mM][dD]} text eol=crlf *.{bat,[bB][aA][tT]} text eol=crlf

Opened up a PR here: #42. I'm new to all of this, so there's a probability something can be wrong with the PR (and in that case I'm sorry, everyone has to learn somehow).

Thanks for considering this.

Add support for Vercel Edge functions

Note: I know there is an issue specifically for Netlify Edge workers but I get a different error with Vercel, see below.

I'm trying to deploy a simple test project to Vercel using Edge functions and the official Astro adapter.

// astro.config.mjs
import { defineConfig } from 'astro/config'

import astroI18next from 'astro-i18next'
import vercel from '@astrojs/vercel/edge'

export default defineConfig({
	integrations: [astroI18next()],
	output: 'server',
	adapter: vercel()
})

package.json

{
	"dependencies": {
		"@astrojs/vercel": "^2.3.5",
		"astro": "^1.6.13",
		"astro-i18next": "1.0.0-beta.14",
		"i18next": "^22.0.8",
		"i18next-fs-backend": "^2.0.1"
	}
}

When deploying (or building locally), I get the following error:

05:34:45 PM [build] Building server entrypoints...
18:34:46.364 | [commonjs--resolver] Cannot bundle Node.js built-in "module" imported from "node_modules/.pnpm/[email protected][email protected]/node_modules/astro-i18next/dist/index.js". Consider disabling ssr.noExternal or remove the built-in dependency.
18:34:46.791 | error   Cannot bundle Node.js built-in "module" imported from "node_modules/.pnpm/[email protected][email protected]/node_modules/astro-i18next/dist/index.js". Consider disabling ssr.noExternal or remove the built-in dependency.
18:34:46.792 | Error: Cannot bundle Node.js built-in "module" imported from "node_modules/.pnpm/[email protected][email protected]/node_modules/astro-i18next/dist/index.js". Consider disabling ssr.noExternal or remove the built-in dependency.
18:34:46.792 | at error (file:///vercel/path0/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/es/shared/rollup.js:1858:30)
18:34:46.792 | at throwPluginError (file:///vercel/path0/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/es/shared/rollup.js:21587:12)
18:34:46.792 | at Object.error (file:///vercel/path0/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/es/shared/rollup.js:22541:20)
18:34:46.792 | at Object.resolveId (file:///vercel/path0/node_modules/.pnpm/[email protected]/node_modules/vite/dist/node/chunks/dep-5605cfa4.js:33615:34)
18:34:46.793 | at Object.handler (file:///vercel/path0/node_modules/.pnpm/[email protected]/node_modules/vite/dist/node/chunks/dep-5605cfa4.js:45912:19)
18:34:46.793 | at file:///vercel/path0/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/es/shared/rollup.js:22748:40

It would be great to be able to do SSR with Vercel! Thanks for this project

Allow setting `fallbackLng` for i18next config

I would like to disable fallbackLng in the i18next config, and instead fall back on using the key directly as the value on the page. However, astro-i18next forces the value of fallbackLng to be supportedLanguages, overriding what I put in my config for i18next.fallbackLng.

If a user explicitly specifies a fallbackLng value, it should be honored instead of overwriting it with supportedLanguages.

i18next client side is not initialized without a UI framework

Hi!

This is a follow up to: #37 (comment)

Basic example of this is created here: https://github.com/dallyh/astro-i18n-client-server-example-react which is basically the astro-i18next React example slightly modified.

  • folder react is with the Counter react component added on the pages.
    • i18next is in this case set to detect language with query string and or path (and both work when there's a react component ready and hydrated). Also i18next logs to browser console.
  • folder without-react-component is the same as react but just without the Counter component on the pages.
    • i18next is in this case is set the same way, but now there is no console output

In both cases strings which are on the Astro pages are translated server side when the server is run or the project is built, which means they are not dynamic in any way for ex. that the URL query (?lng=XX) does not change them (and that is fine).

Basically what happens is that i18next does not get loaded client side, when there's no UI framework present and hydrated on a page. I guess that this makes sense, because i18n runs with injectScript: before-hydration, and when there is nothing to hydrate, then, i18n just doesn't load.

Although this makes sense to me, I would like to have this confirmed, and maybe added to the documentation.

Thanks a lot!

Exclude generated pages from source control?

Any best practices here folks can share? Seems wrong to generate pages before checking in changes to source control..

Better yet, any plans to just automatically generate pages during the build process and NOT inject them into the source?

Netlify deploy with SSR

Hello. I'm trying to use this package together with SSR functionalities on Netlify.

Without SSR features everything works. When i plugin the Netlify adapter the deployment phase fails with this error:
2022-08-27 (1)

Set translated slugs

Let's say I have this page in two languages:

  • /contacts
  • /it/contatti

How can I set translated slugs inside a page? Translated slugs comes from an API call from a headless CMS

client locale path broken

Hi, I've setup astro-i18next for server and client (see florian-lefebvre/portfolio@f303ac8) and it works for the default locale.
I had to setup custom paths because of #79.

So when I switch to French, wrong paths are loaded:

22:24:58 [serve]    404      /fr/src/locales/fr/translation.json
22:24:58 [serve]    404           /fr/src/locales/fr/common.json
22:24:58 [serve]    404      /fr/src/locales/fr/pages.index.json
22:24:58 [serve]    404   /fr/src/locales/fr/pages.projects.json
22:24:58 [serve]    404      /fr/src/locales/en/translation.json
22:24:58 [serve]    404           /fr/src/locales/en/common.json
22:24:58 [serve]    404      /fr/src/locales/en/pages.index.json
22:24:58 [serve]    404   /fr/src/locales/en/pages.projects.json

Looks like './src/locales/...' in config.i18nextClient.backend.loadPath become '/{{lng}}/src/locales/...'

cli "npx astro-i18next generate" does not update imports for generated files

I'm facing import related issues when firing the npx astro-i18next generate command

for any other import such as the component import i have alias based import like import AboutUsHiringSection from '@/components/astro/AboutUsHiringSection.astro' which is fine, but the rest of import needs to be updated in order to go back one level below since it's generating a dedicated directory for every defined locale

My index.astro

<script>
  import '../scripts/pageBackgroundChanger.ts'
</script>

Expected: /pages/en/index.astro

<script>
  import '../../scripts/pageBackgroundChanger.ts'
</script>

Generated: /pages/en/index.astro

<script>
  import '../scripts/pageBackgroundChanger.ts'
</script>

the cli isn't updating accordingly, same issue with another page that uses Astro.glob to fetch markdown files

My /pages/hiring.astro
await Astro.glob('../content/hiring-*.mdx')

Expected: /pages/en/hiring.astro
await Astro.glob('../../content/hiring-*.mdx')

Generated /pages/en/hiring.astro
await Astro.glob('../content/hiring-*.mdx')

Don't transform paths that start with an underscore

The Astro docs say

You can exclude pages, or even whole directories from being built by prefixing their names with an underscore (_).

This allows you to create private pages, and also to co-locate tests, utilities, and components with their related pages, preventing them from being built into .html files and placed into the dist/ directory.

It seems to me that astro-i18next should ignore any directories/files that begin with an underscore, and update any relative imports in non-excluded page files to point to the original excluded file path.

Support implicit key for <Trans> component

Feature request

Automatically generate a value for i18nKey if the prop is omitted based on the contents of the element.

Background

The react-i18next docs say about the <Trans> component's i18nKey prop

If you prefer to use text as keys you can omit this, and the translation will be used as key

The i18nKey prop in astro-i18next's <Trans> component is not optional. You need to specify a i18nKey manually. I would like this prop to be optional, and to generate a value automatically.

Helper functions localizePath and localizeUrl does not take base into account

First of all thanks for this plugin and amazing work!

When using helper functions localizePath and localizeUrl with a "base" set in astro config like this:

site: "https://www.somesite.com", base: "/base"

then those functions do not redirect to the correct path.

Let's take a look at this example with "cs" set as language. URL in this case now looks like this: https://somesite.com/base/cs.

localizePath("/somepage")

or

localizePath("/base/somepage")

redirects to https://somesite.com/cs/somepage and https://somesite.com/cs/base/somepage respectively, which does not resolve to anything.

Function localizeUrl does the same. Again let's say we are on page with URL https://somesite.com/base/ which is now a default language and I want to change to "cs" language. I'm using the language picker component, which uses this function with the help of const { pathname } = Astro.url which in this case returns the base, which is /base/. After a change to "cs - Czech", now the URL looks like this https://somesite.com/cs/base.

Am I just missing something, and using them wrong? Thanks!

`generate` may need to put `changeLanguage` at the top

Hi, thanks for your excellent work.

I just use this to imply my blog's i18n. But I come across a problem.

On my index page, I want to map a slice of /{i18next.language}/blog/{slug}.md to a list to show my recent posts. But the generated changeLanguage is at the bottom of the frontmatter. Thus I cannot get the correct language before my code.

My code:

// src/pages/index.astro
import Base from "@layouts/Base.astro"
import Icon from "astro-icon"
import i18next, { t, changeLanguage } from "i18next"
import { localizePath } from "astro-i18next"
const posts =
  i18next.language === "en"
    ? (await Astro.glob("/src/pages/en/blog/*.{md,mdx}"))
        .sort(...)
        .slice(0, 3)
    : (await Astro.glob("/src/pages/blog/*.{md,mdx}"))
        .sort(...)
        .slice(0, 3)

// generated code at the bottom
changeLanguage("zh")

My config:

/** @type {import('astro-i18next').AstroI18nextConfig} */
export default {
  defaultLanguage: "zh",
  supportedLanguages: ["zh", "en"],
  i18next: {
    debug: true,
    initImmediate: false,
    backend: {
      loadPath: "./src/locales/{{lng}}.json",
    },
  },
  i18nextPlugins: {
    fsBackend: "i18next-fs-backend",
  },
}

IMO, changeLanguage may need to be at the top, something like:

// import part
changeLanguage("zh")
// other codes

Different strategies for routing path generation

I have searched and couldn't find anything on this, but by default the plugin is assuming a prefix except default strategy for routing, meaning that in a project with it, en and fr languages, with it as default you'd have.

/blog  --> Italian
/en/blog  --> English
/fr/blog  --> French

I'd love to be able to change this so that all languages are under their {language_id} path and auto-redirect the non prefixed paths to the default (or to the chosen language by the user).

This could help with consistency for sure, but also keeping URLs aligned especially with the new route translations feature.

changeLanguage does not work form within react components

Hi, I am not sure if this actually should work, but I tried to create a client side langauge switcher:

import {changeLanguage} from 'i18next';

const LanguageSwitch = () => {
  return (
    <div>
      <button onClick={() => changeLanguage('de')}>DE</button>
      <button onClick={() => changeLanguage('en')}>EN</button>
    </div>
  );
};

export default LanguageSwitch;

the command astro-i18next generate works as intended, so I think I set up the module correctly. But when I click the buttons, the language is not actually changed.

Not sure if this is a bug, or if I should actually do this differently. If there is a different intended way to do this, it would be great to have it in the documentation :)

Astro.canonicalURL is deprecated

[deprecation] Astro.canonicalURL is deprecated! Use `Astro.url` instead.
Example:

---
const canonicalURL = new URL(Astro.url.pathname, Astro.site);
---

[deprecation] Astro.canonicalURL is deprecated! Use `Astro.url` instead.

I'm currently using astro version @1.0.6.

In this version it's not possible to use Astro.canonicalURL anymore, wich leads into the following error when I try to use this integration:

Invalid URL at new NodeError (node:internal/errors:372:5) at URL.onParseError (node:internal/url:553:9) at new URL (node:internal/url:629:5) at Object.get (file:///D:/mhraschan_v2_astro/node_modules/astro/dist/core/render/result.js:200:18) at D:/mhraschan_v2_astro/node_modules/astro-i18next/dist/components/HeadHrefLangs.astro:1:0 at Module.renderToIterable (/node_modules/astro/dist/runtime/server/render/astro.js:73:27) at renderAstroComponentInline (/node_modules/astro/dist/runtime/server/render/component.js:69:29) at renderAstroComponentInline.next (<anonymous>) at Module.renderChild (/node_modules/astro/dist/runtime/server/render/any.js:20:5) at async AstroComponent.[Symbol.asyncIterator] (/node_modules/astro/dist/runtime/server/render/astro.js:31:7)

The issue comes down to HeadHrefLangs.astro and LanguageSelector.astro.

It needs to be changed to Astro.url

Edit:
I saw that this error is fixed on develop but not on the beta branch which is currently out on npm

Offline Support/Service Worker integration

I've always thought it would be cool to see a translation lib with support for service workers. Why does this combination make sense? Well mainly because if you have a whole bunch of translations trying to download a website offline potentially makes the bundle size massive if you have to download it in every language. It would be really cool to have some kind of feature that would make it easy for users to download the site in the language(s) of their choice for offline use.

Move more docs to the site instead of the Readme?

It's going to become more difficult to read the bigger the Readme becomes. It might look nice and make sense to move the docs to it's own website

Edit: I just saw this was on your list already sorry, also I would be willing to help if you'd like

Support for PNPM (astro-i18next throws with "module is not defined")

When I try to use <Trans />, <HeadHrefLangs />, <LanguageSelector />, interpolate, etc I get the following error :

module is not defined

/@fs/my/local/directories/turborepo-astro-nestjs/node_modules/.pnpm/[email protected]/node_modules/deepmerge/dist/cjs.js:133:1

ReferenceError: module is not defined
    at /my/local/directories/turborepo-astro-nestjs/node_modules/.pnpm/[email protected]/node_modules/deepmerge/dist/cjs.js:133:1
    at instantiateModule (file:///my/local/directories/turborepo-astro-nestjs/node_modules/.pnpm/[email protected]/node_modules/vite/dist/node/chunks/dep-db16f19c.js:53436:15

I'm using pnpm and turborepo, reproduction (error at apps/frontend/src/layouts/Layout.astro line 2 & 19):
https://github.com/Alexandre-Fernandez/turborepo-astro-nestjs

Astro app is located in /apps/frontend, commands to get the error :

EDIT:

This might happen because it's trying to load from the monorepo root /node_modules instead of its corresponding workspace /apps/frontend/node_modules.
I say that because I get a different error (another missing dependency) when I install [email protected] in the root package.json (pnpm add [email protected] -w).
This only happens with astro-i18next and not with i18next.

Generate is removing import names

I have tried to follow the setup steps and I had a few problems:

  1. I needed to rename astro-i18next.config.js to astro-i18next.config.mjs
  2. when I run npx astro-i18next generate the existing astro file is modified and the new language one has the same issue - import statements by name are being corrupted. Example:

`import Layout from "../layouts/Layout.astro";
import Card from "../components/Card.astro";

// becomes
import "../layouts/Layout.astro" from ;
import "../components/Card.astro" from ;`

How to load individual namespaces

Problem

I'm trying to split up my translations into namespaces and I kept getting the following error:

i18next::backendConnector: did not save key "globalTitle" as the namespace "common" was not yet loaded This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!

After a lot of digging, I realized this is because I forgot this line from my i18next config, which isn't mentioned anywhere in the "namespace" part of the astro-i18next documentation:

    ns: ['common'],

This tells i18next to load those namespaces when it initializes. The ns array must have all in-use namespaces listed in order for those namespaces to be available for translation.

Suggested solutions

Option 1

Document what to do if this error happens, and how to load namespaces explicitly

Option 2

Automatically load all namespaces as part of astro-i18next's setup

Option 3

Document (or implement if not currently possible) the ability to load specific namespaces at the top of specific page (or component) files.


My personal preference is option 3. Unlike a client-rendered app, loading only specific namespaces doesn't have a runtime performance benefit. However, it does help encourage namespace organization/segregation if desired.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.