Git Product home page Git Product logo

lib's Introduction

npm version

sveltekit-i18n

sveltekit-i18n is a tiny library with no external dependencies, built for Svelte and SvelteKit. It glues @sveltekit-i18n/base and @sveltekit-i18n/parser-default together to provide you the most straightforward sveltekit-i18n solution.

Key features

✅ SvelteKit ready
✅ SSR support
✅ Custom data sources – no matter if you are using local files or remote API to get your translations
✅ Module-based – your translations are loaded for visited pages only (and only once!)
✅ Component-scoped translations – you can create multiple instances with custom definitions
✅ Custom modifiers – you can modify the input data the way you really need
✅ TS support
✅ No external dependencies

Usage

Setup translations.js in your lib folder...

import i18n from 'sveltekit-i18n';

/** @type {import('sveltekit-i18n').Config} */
const config = ({
  loaders: [
    {
      locale: 'en',
      key: 'common',
      loader: async () => (
        await import('./en/common.json')
      ).default,
    },
    {
      locale: 'en',
      key: 'home',
      routes: ['/'], // you can use regexes as well!
      loader: async () => (
        await import('./en/home.json')
      ).default,
    },
    {
      locale: 'en',
      key: 'about',
      routes: ['/about'],
      loader: async () => (
        await import('./en/about.json')
      ).default,
    },
    {
      locale: 'cs',
      key: 'common',
      loader: async () => (
        await import('./cs/common.json')
      ).default,
    },
    {
      locale: 'cs',
      key: 'home',
      routes: ['/'],
      loader: async () => (
        await import('./cs/home.json')
      ).default,
    },
    {
      locale: 'cs',
      key: 'about',
      routes: ['/about'],
      loader: async () => (
        await import('./cs/about.json')
      ).default,
    },
  ],
});

export const { t, locale, locales, loading, loadTranslations } = new i18n(config);

...load your translations in +layout.js...

import { loadTranslations } from '$lib/translations';

/** @type {import('@sveltejs/kit').Load} */
export const load = async ({ url }) => {
  const { pathname } = url;

  const initLocale = 'en'; // get from cookie, user session, ...

  await loadTranslations(initLocale, pathname); // keep this just before the `return`

  return {};
}

...and include your translations within pages and components.

<script>
  import { t } from '$lib/translations';

  const pageName = 'This page is Home page!';
</script>

<div>
  <!-- you can use `placeholders` and `modifiers` in your definitions (see docs) -->
  <h2>{$t('common.page', { pageName })}</h2>
  <p>{$t('home.content')}</p>
</div>

More info

Docs
Examples
Changelog

lib's People

Contributors

bartduisters avatar dependabot[bot] avatar github-actions[bot] avatar jarda-svoboda avatar kamerat avatar swepool 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

lib's Issues

"svelte-kit dev is no longer available — use vite dev instead" error

Hello,

I have this error "svelte-kit dev is no longer available — use vite dev instead":

/home/stephane/git/github.com/sveltekit-i18n/lib/examples/single-load
$ npm install
npm WARN ignoring workspace config at /home/stephane/git/github.com/sveltekit-i18n/lib/examples/single-load/.npmrc

up to date, audited 589 packages in 843ms

89 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities
$ npm run dev
npm WARN ignoring workspace config at /home/stephane/git/github.com/sveltekit-i18n/lib/examples/single-load/.npmrc

> [email protected] dev
> svelte-kit dev

(⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂⠂) ⠧ : timing config:load:flatten Completed in 1ms
> svelte-kit dev is no longer available — use vite dev instead
  1. Install vite as a devDependency with npm/pnpm/etc
  2. Create a vite.config.js with the @sveltejs/kit/vite plugin (see below)
  3. Update your package.json scripts to reference `vite dev` instead of `svelte-kit dev`

// vite.config.js
import { sveltekit } from '@sveltejs/kit/vite';

/** @type {import('vite').UserConfig} */
const config = {
        plugins: [sveltekit()]
};

export default config;


npm ERR! Lifecycle script `dev` failed with error:
npm ERR! Error: command failed
npm ERR!   in workspace: [email protected]
npm ERR!   at location: /home/stephane/git/github.com/sveltekit-i18n/lib/examples/single-load

Best regards,
Stéphane

Argument types do not match parameters

If I use $t in a script element like this:

<script lang="ts">
	import {t} from '$lib/i18n';

	export let placeholder = $t('search.placeholder');
</script>

PhpStorm shows an error:

Argument types do not match parameters

Placing it inside the template/HTML part …

<input placeholder={$t('search.placeholder')}/>

… does not.

I'm not sure this is a problem with sveltekit-i18n, but I have no idea why this happens. The translation is actually working, it is just the IDE complaining and marking files as erroneous.

"İ" doesn't change to "I" when the language is changed

"i" and "ı" are two different letters in most Turkic languages.
Capital form of "i" is "İ" and "ı" is "I".

When I use uppercase form of string (by using CSS: text-transform: uppercase;), they don't change according to language standard. My browser is the latest version of Chrome. I don't define custom font, I use system default font.

For example:
<div style="text-transform: uppercase">This is my text</div>

  1. If the language is English when I first load the page:
    Output: THIS IS MY TEXT
    This is as expected.

  2. When I change language to Azerbaijani:
    Output: THIS IS MY TEXT
    But it should be: THİS İS MY TEXT

Testing vice-versa:

  1. If the language is Azerbaijani when I first load the page:
    Output: THİS İS MY TEXT
    This is as expected.

  2. When I change language to English:
    Output: THİS İS MY TEXT
    But it should be: THIS IS MY TEXT

This ambiguity occur only when I use text-transform: uppercase;. I don't get this problem if I type uppercased letters by hand. But I can't use this method in each page (project requirements). How can I solve this issue?

I don't really know if this is related to the sveltekit-i18n or not. I am sorry if I am in a wrong place for this issue :)

ICU parser example not work

ICU parser example is not building (dev works).
npm run build fails with: SyntaxError: Named export 'IntlMessageFormat' not found. The requested module 'intl-messageformat' is a CommonJS module, which may not support all module.exports as named exports.

Full output:

druid@knieja:~/Pulpit/tmp/lib/examples/parser-icu$ npm run build

> [email protected] build
> svelte-kit build

vite v2.9.13 building for production...
✓ 36 modules transformed.
  Client build completed. Wrote 9 chunks and 1 assets
  Building server
.svelte-kit/output/client/_app/immutable/manifest.json                       2.00 KiB
.svelte-kit/output/client/_app/immutable/pages/__layout.svelte-1146874d.js   2.18 KiB / gzip: 1.13 KiB
.svelte-kit/output/client/_app/immutable/error.svelte-8c29fdbe.js            1.56 KiB / gzip: 0.75 KiB
.svelte-kit/output/client/_app/immutable/pages/index.svelte-006300e9.js      2.88 KiB / gzip: 1.35 KiB
.svelte-kit/output/client/_app/immutable/chunks/preload-helper-beb8b45d.js   1.34 KiB / gzip: 0.81 KiB
.svelte-kit/output/client/_app/immutable/start-cb19f3d3.js                   22.30 KiB / gzip: 8.35 KiB
.svelte-kit/output/client/_app/immutable/chunks/content-03638256.js          0.48 KiB / gzip: 0.29 KiB
.svelte-kit/output/client/_app/immutable/chunks/index-eb7ba480.js            7.60 KiB / gzip: 3.09 KiB
.svelte-kit/output/client/_app/immutable/chunks/content-5d443e23.js          0.46 KiB / gzip: 0.29 KiB
.svelte-kit/output/client/_app/immutable/chunks/index-02ba6100.js            47.28 KiB / gzip: 14.33 KiB
vite v2.9.13 building SSR bundle for production...
✓ 17 modules transformed.
Generated an empty chunk: "hooks"
.svelte-kit/output/server/manifest.json                       1.68 KiB
.svelte-kit/output/server/index.js                            72.74 KiB
.svelte-kit/output/server/entries/pages/__layout.svelte.js    1.02 KiB
.svelte-kit/output/server/entries/fallbacks/error.svelte.js   0.72 KiB
.svelte-kit/output/server/entries/pages/index.svelte.js       1.74 KiB
.svelte-kit/output/server/chunks/index-2580c06c.js            3.42 KiB
.svelte-kit/output/server/chunks/index-8da469ab.js            13.23 KiB
.svelte-kit/output/server/chunks/hooks-1c45ba0b.js            0.00 KiB
.svelte-kit/output/server/chunks/content-03638256.js          0.55 KiB
.svelte-kit/output/server/chunks/content-5d443e23.js          0.53 KiB
  Prerendering
file:///home/druid/Pulpit/tmp/lib/examples/parser-icu/node_modules/@sveltekit-i18n/parser-icu/dist/index.js:1
import{IntlMessageFormat as p}from"intl-messageformat";var f=e=>({parse:(r,[t,o],a,n)=>r===void 0?`${n}`:new p(r,a,o,e).format(t)}),u=f;export{u as default};
       ^^^^^^^^^^^^^^^^^
SyntaxError: Named export 'IntlMessageFormat' not found. The requested module 'intl-messageformat' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:

import pkg from 'intl-messageformat';
const {IntlMessageFormat: p}from"intl-messageformat";var f=e=>({parse:(r,[t,o],a,n)=>r===void 0?`${n}`:new p(r,a,o,e).format(t)}),u=f;export{u: default} = pkg;

    at ModuleJob._instantiate (node:internal/modules/esm/module_job:127:21)
    at async ModuleJob.run (node:internal/modules/esm/module_job:191:5)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:331:24)
    at async Promise.all (index 0)
    at async respond$1 (file:///home/druid/Pulpit/tmp/lib/examples/parser-icu/.svelte-kit/output/server/index.js:1751:13)
    at async resolve (file:///home/druid/Pulpit/tmp/lib/examples/parser-icu/.svelte-kit/output/server/index.js:2140:105)
    at async respond (file:///home/druid/Pulpit/tmp/lib/examples/parser-icu/.svelte-kit/output/server/index.js:2095:22)
    at async visit (file:///home/druid/Pulpit/tmp/lib/examples/parser-icu/node_modules/@sveltejs/kit/dist/vite.js:1121:20)
SyntaxError: Named export 'IntlMessageFormat' not found. The requested module 'intl-messageformat' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:

import pkg from 'intl-messageformat';
const {IntlMessageFormat: p}from"intl-messageformat";var f=e=>({parse:(r,[t,o],a,n)=>r===void 0?`${n}`:new p(r,a,o,e).format(t)}),u=f;export{u: default} = pkg;

[vite-plugin-svelte-kit] 500 /
> 500 /
    at file:///home/druid/Pulpit/tmp/lib/examples/parser-icu/node_modules/@sveltejs/kit/dist/vite.js:1020:11
    at save (file:///home/druid/Pulpit/tmp/lib/examples/parser-icu/node_modules/@sveltejs/kit/dist/vite.js:1239:4)
    at visit (file:///home/druid/Pulpit/tmp/lib/examples/parser-icu/node_modules/@sveltejs/kit/dist/vite.js:1130:3)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

Steps to reproduce:

  1. follow instrunctions from readme (clone, cd to ./parser-icu), install latest sveltekit-i18n/base
  2. run npm run build to make a production build

npm: 8.1.2
node: v17.1.0
vite: 2.9.13
typescript: 4.6.4
tslib: 2.4.0
svelte: 3.48.0
sveltejs/kit: 1.0.0-next.355

SEO friendly default locale routes

Wondering if this project will be able to autogenerate routes like @nuxtjs/i18n ?
And also support that the default locale will not have a prefix.
The current locale-router example does not support removing prefix for the default locale.

If it is not possible autogenerate the routes, how could I make the default locale not have prefix with the current solution? Maybe duplicate all pages in [lang] and move it directly in pages?

Export Modifier and Parser declarations

Currently, Modifier nor Parser type declarations are exported from sveltekit-i18n so devs need to import them from @sveltekit-i18n/parser-default instead. For better DX it would be nicer to have these declarations exported directly from sveltekit-i18n package.

Store selection

If a user selects a language, is it possible to remember this and redirect to selected language?

I'm using local-router

Unable to get raw translations

Alternative libraries like svelte-i18n include the ability to get raw translation JSON (T in this case). This is useful when translating lists of items, for instance countries. Workarounds either cause extra fetches or break the nice abstractions of this library, so it'd be great to have a raw method or something that gives out raw Ts.

Routes bug

We currently have pages like so: …/en/about. But the routes located in the configuration either doesn’t work like /about or /en/about. Is there a possible fix for this?

The current homepage /en also doesn’t work with the i18n routes exampled here: routes: ['/','en','/en/','/en']

locale is transformed to lowercase

I am working on pretty big project reworking it from svetle-i18n and we are using locale when saving items to database, so previously we saved every locale in uppercase format and now if i implement this package it breaks everything across the project, because it transforms current locale to lowercase. I think that locale should be kept in same format as it is defined in loaders (key locale).

const config = {
  parser: parser({ ignoreTag: true }),
  loaders: [
    {
      locale: 'CS',
      key: '',
      loader: async () => (await import('localization/messages/cs.json')).default,
    },
    {
      locale: 'EN',
      key: '',
      loader: async () => (await import('localization/messages/en.json')).default,
    },
  ],
};

[i18n]: Non-standard locale provided:

Been trying to figure this one out, can't seem to find where it's coming from?
Non-standard locale provided: 'static'. Check your 'translations' and 'loaders' in i18n config...

Translations in stores and objects does not change when locale is changed

When i change locale like this locale.set(newLocale), the translations change only in some places. If i have translations in some store, they do not change. I have layout store which has setHeader method and if i call it like this setHeader({ title: $t('settings.title') }); and then change locale, this tranlations does not change (until page is refreshed).
Same problem is happening when I create array of objects and key in this object is translation, when i render components from this object, the translations will not update after locale change.
Object example:

const navItems= [
    {
      label: $t('home.title'),
      target: '/home',
    },
    {
      label: $t('about.title'),
      target: '/about',
    },
]

Usage example:

{#each navItems as item}
    <NavButton
       {...item}
    />
 {/each}

In NavButton i am using the passed prop like this: <span>{label}</span>

I think that it realtime translates only things in svelte component it html section within $t() function, but if you have translation stored somewhere else and in component you only want to render it without $t() than it works only after page refresh, not on locale change

Open FAQ in Discussions to guide newcomers

Topics should include:

  • how to use the library
  • differences in config between sveltekit-i18n and @sveltekit-i18n/base with @sveltekit-i18n/parser-default
  • how to use different (ICU / custom) message syntaxes

concurrent requests will lead to inconsistent `$t` store

Hey, I just stumbled accross your library and I think you will have the same problem like I had with my i18n library typesafe-i18n.

When having multiple parallel requests, the store could change before the first request is completed, leading in a wrong locale beeing rendered. See here for more details: ivanhofer/typesafe-i18n#159

I want to replicate it using one of your examples, but I could not install the sveltekit-i18n dependencies. I think something is currently broken...

Introduce connectors

It would be cool to have Google Translation API connector (and others) for direct text translations.

Undefined keys leak into the page

When using the $t or $l functions or their .get() counterparts, if the translation key is not found it leaks into the page as-is. I would prefer for the function to instead return a falsy value such as undefined . Can I achieve this behaviour somehow?

Single translation file per language

Thanks for the library.

Is it possible to have just one file per language? I have just a few texts per page and it doesn't make much sense to have then separate files. I'd like to use a js file instead of json and separate the pages with comments.

I tried this config

const lang = { en: 'English', cs: 'Česky' }
export const config = {
  translations: { en: { lang }, cs: { lang } },
  loaders: [
    { locale: 'en', loader: async () => await import('./en.js') },
    { locale: 'cs', loader: async () => await import('./cs.js') }
  ]
}

it doesn't throw any errors but the t method just returns the argument string.

Provide a way to use custom message parsers

As mentioned in #28 it would be useful to extract parser from this lib to separate package so every developer could use any parser (and message format) they want.

This process should consist of these steps:

  • extract base functionality of this library to base repository
  • extract currently used parser to parsers/parser-default
  • keep this repository to glue the base and the parser-default together to prevent API changes
  • update docs
  • update tests

Hiding time in {{value:date}}

Is there any way to hide the time in a {{value:date}} in parser-default?

{$t("app.modifier_date", { value: new Date(contract.starts_at) } )}

I am getting Jan 4, 2022, 11:34 AM, and what I would like to get is just Jan 4, 2022

Thanks in advance,
J.

Security issue with duplicit-load-prevention example

Hi!

The duplicit-load-prevention example is subject to XSS injection.

The example add a /addTranslations route that seems to modify the translations stored in memory.

How to reproduce:

  • Start sveltekit in the example: npm run preview
  • call /addTranslations manually, with a malicious value for home.text:
curl 'http://localhost:3000/addTranslations' -X POST -d '{
    "translationProps":[
        {"en":
            {"menu.home":"home",
                "menu.about":"About",
                "menu.notification":"You have {{count:gt; 0:{{count}} new {{count; 1:message; default:messages}}!; default:no messages...}}",
                "home.title":"Welcome to SvelteKit",
                "home.text":"<script>alert(\"Malicious\")</script>Visit <a href=\"{{link}}\">kit.svelte.dev</a> to read the documentation"
            }
        },{"en":["menu",
                "home"]}]
}'

Results:

image

I don't really understand duplicit-load-prevention example but, considering the risk of using it, I think it should be removed from this repo (and maybe advertise that addTranslations() sould never be called with input from an untrusted source).

Is it possible to implement a fallback locale?

I tried the following code, but failed.

export const config = {
  loaders: [
    { locale: 'en', key: '', 
      loader: () => ({ 'titles.trip': 'Trips', 'titles.events': 'Reports', 'titles.events': 'Events' })
    },
    { locale: 'zh-Hans', key: '', 
      loader: () => ({ 'titles.trip': '旅行' })
    },
  ]
};
export const { t, l, locale, locales, loading, loadTranslations } = new i18n(config);

await loadTranslations('zh-Hans', '/');

const fallbackLocale = 'en';

const tr = (key, ...args) => {
  const message = $t(key, ...args);
  return (key === message) ? $l(fallbackLocale, key, ...args) : message;
}

// output
// $locale = zh-Hans
// $locales = (3) ['en', 'zh-Hans', 'zh-hans']

tr('titles.trip')  '旅行'  OK
tr('titles.report')  'titles.report'  Not 'Reports'
tr('titles.events')  'titles.events'  Not 'Events'

Why $locales is not ['en', 'zh-Hans']?
$l(locale, key) is working?

Thank you.

Translation when importing components after translations

Vite compiler is puking when I try to add translations before the button component.

<script>
  import { t } from "$lib/translations";
  import Button from "../components/base/Button.svelte";

</script>

<Button>{$t("common.menu.booking")}</Button>

This is my lang file setup

import i18n from "sveltekit-i18n";
import lang from "./lang.json";
export const config = {
  translations: {
    en: { lang },
    da: { lang },
    se: { lang },
  },
  loaders: [
    {
      locale: "en",
      key: "common",
      loader: async () => (await import("./en/common.json")).default,
    },
    {
      locale: "da",
      key: "common",
      loader: async () => (await import("./da/common.json")).default,
    },
    {
      locale: "se",
      key: "common",
      loader: async () => (await import("./se/common.json")).default,
    },
  ],
};

export const { t, locale, locales, loading, loadTranslations } = new i18n(
  config
);

loading.subscribe(
  ($loading) => $loading && console.log("Loading translations...")
);

Vite error:

Internal server error: Cannot find module 'C:\Projects\projectname\package.json' imported from 'C:\Projects\projectname\node_modules\vite\dist\node\chunks\dep-f5552faa.js'

I'm using sveltekit with svelte add and Tailwind

How to set a default or fallback key and language?

I am needing a way to specify default language as "en" (if we don't have a language file for example). In addition I need a way to default the using the key if no entry exists.

For example I use "$t('Welcome')" as my key, if no language code file or no entry for "Welcome" exists it should just default to the key (which is "Welcome").

How do I do this?

Typescript: locale type Improvement

export const { t, locale, locales, loading, loadTranslations } = new i18n(config);

locale exposes a svelte store which is used to get/set the locale throughout the app. However, the type on it is weak (string).

It should be possible to infer the locale Type more strongly using the configuration provided?

default language ignored

I changed default language in firefox from English to German and i'm still only seeing english translations.

I checked navigator.language in console and it correclty says de

Loader for route with params

Not really an issue but more of a question.
You specify in the main README.md that a loader can use regex to specify a route :

    // ...
    {
      locale: 'en',
      key: 'home',
      routes: ['/'], // you can use regexes as well!
      loader: async () => (
        await import('./en/home.json')
      ).default,
    },
    // ...

I'm guessing that's how you handle routes with params, I just wanted to know if you can confirm this or if there's a better way. I didn't find this in examples or in any of the READMEs.

Thanks for this library.

locale-router example typo

Hello!
I found a typo on this line, it should be request.headers.get('accept-language') instead of request.headers['accept-language'].
Here is a link for the same issue.
Thanks for your work ❤️

No translation key or locale provided. Skipping translation...

Hi,

I've been using sveltekit-i18n successfully today. After adding two lines of unrelated code the app wouldn't translate anymore with the following error:

No translation key or locale provided. Skipping translation...

Commenting out the new code didn't solve the problem. Reinstalling the package didn't either. I even replaced all the translation related code with the one provided in the README with no success.

Other than the i18n package the app is still empty. What can this error mean?

Thanks

Use custom stores

Currently, svelte/store is used to store library data, but relying on Svelte's stores is not necessary. This lib could work even without using svelte dependency.

what is key: 'common', used for?

Is it reuqired? I don't see it used for anything.

I have a simple /lang/en.json with key/value json object....but its not working all that t('foo') shows it the key, not a value from lang file.

Sapper support?

I'm not sure there is anything that keeps this lib from being used in Sapper as well. I tried the simple example that is provided but with Sapper specific tweaks (_layout instead of __layout, preload instead of load, path instead of url.pathname) and it seem to almost work. The SSR:d content is translated as expected but the frontend renders empty translations (after a quick flash of the correct SSR:d content). I also get the warning [i18n]: No translation key or locale provided. Skipping translation... in the browser.
Am I missing something simple or is Sapper support harder than I expect?

Typescript payload not inferred in "new i18n"

Unless I'm missing something, new i18n(config) does not infer the type of Params from config so @sveltekit-i18n/parser-default needs to be imported just to get the Parser type to declare it explicitly.

For translations.ts I am forced to do this so that my type checking doesn't return an error:

import i18n from 'sveltekit-i18n';
import type { Config } from 'sveltekit-i18n';
import type { Parser } from '@sveltekit-i18n/parser-default';

export const defaultLocale = 'en';

export interface Payload extends Parser.PayloadDefault {
    placeholder?: string;
}

const config: Config<Payload> = {
   ...
};

export const { t, locale, locales, loading, loadTranslations, translations } = new i18n<
    Parser.Params<Payload>
>(config);

If I don't include <Parser.Params<Payload>>, I get an error that placeholder doesn't exist when passing it to a $t(...).

is the lib prepared to deal with translations of numbers and dates?

I have been trying your lib, and it works really nice. Thank you.
I need to translate the format of dates and numbers (currency), is it the library prepared?
Do you have at hand any example how to do so with this lib?

For example:

<div>{$number(100000000)}</div>
<!-- 100,000,000 -->

<div>{$number(100000000, { locale: 'pt' })}</div>
<!-- 100.000.000 -->

Thank you in advance,
J.

TypeError: Cannot destructure property 'pathname' of 'url' as it is undefined.

Hi, after I copied and pasted code in repo description I get this error.

TypeError: Cannot destructure property 'pathname' of 'url' as it is undefined.
    at __layout.svelte:77:18
    at Generator.next (<anonymous>)
    at eval (/website/src/routes/__layout.svelte:44:66)
    at new Promise (<anonymous>)
    at __awaiter /website/src/routes/__layout.svelte:21:9)
    at load (/website/src/routes/__layout.svelte:142:27)
    at load_node (/website/node_modules/@sveltejs/kit/dist/ssr.js:818:30)
    at respond_with_error (/website/node_modules/@sveltejs/kit/dist/ssr.js:904:23)
    at async respond$1 (website/node_modules/@sveltejs/kit/dist/ssr.js:1119:13)
    at async render_page (/website/node_modules/@sveltejs/kit/dist/ssr.js:1186:20)

Here's my Script tag

	import { locale, loadTranslations } from '$lib/translations';

	export const load = async ({ url }) => {
		const { pathname } = url;

		const defaultLocale = 'en';

		const initLocale = locale.get() || defaultLocale;

		await loadTranslations(initLocale, pathname);

		return {};
	}

__vite_ssr_import_1__.loadTranslations is not a function

Hi, I'm running into issues with this error every time, not sure what's wrong.
I followed the README and the Multi-Page Example.

every time with hot reload will run into

__vite_ssr_import_1__.loadTranslations is not a function
TypeError: __vite_ssr_import_1__.loadTranslations is not a function
    at load (__layout.svelte:11:26)
    at load_node (file://home/tailwind-cms/node_modules/@sveltejs/kit/dist/chunks/index.js:1610:30)
    at respond$1 (file://home/tailwind-cms/node_modules/@sveltejs/kit/dist/chunks/index.js:1812:21)
    at async render_page (file://home/tailwind-cms/node_modules/@sveltejs/kit/dist/chunks/index.js:2003:19)
    at async resolve (file://home/tailwind-cms/node_modules/@sveltejs/kit/dist/chunks/index.js:2159:10)
    at async Object.handle (//Users/xintan/Workspace/Ailink/code/ailink-tailwind-cms/src/hooks:8:19)
    at async respond (file://home/tailwind-cms/node_modules/@sveltejs/kit/dist/chunks/index.js:2123:20)
    at async file://home/tailwind-cms/node_modules/@sveltejs/kit/dist/chunks/index.js:2461:24

then

Error when evaluating SSR module /src/lib/locale/index.js:
TypeError: Class extends value #<Object> is not a constructor or null
    at Object.<anonymous> (/home/tailwind-cms/node_modules/sveltekit-i18n/dist/index.cjs:1:1446)
    at Module._compile (node:internal/modules/cjs/loader:1109:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1138:10)
    at Module.load (node:internal/modules/cjs/loader:989:32)
    at Function.Module._load (node:internal/modules/cjs/loader:829:14)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:201:29)
    at ModuleJob.run (node:internal/modules/esm/module_job:175:25)
    at async Loader.import (node:internal/modules/esm/loader:178:24)
    at async importModuleDynamicallyWrapper (node:internal/vm/module:437:15)
    at async nodeImport (/home/tailwind-cms/node_modules/vite/dist/node/chunks/dep-f5552faa.js:60169:21)

here's my Package file:

"devDependencies": {
    "@sveltejs/adapter-auto": "next",
    "@sveltejs/adapter-static": "^1.0.0-next.26",
    "@sveltejs/kit": "next",
    "autoprefixer": "^10.4.2",
    "eslint": "^7.32.0",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-svelte3": "^3.2.1",
    "postcss": "^8.4.5",
    "prettier": "^2.4.1",
    "prettier-plugin-svelte": "^2.4.0",
    "svelte": "^3.44.3",
    "tailwindcss": "^3.0.17"
  },
  "type": "module",
  "dependencies": {
    "@fontsource/fira-mono": "^4.5.0",
    "@lukeed/uuid": "^2.0.0",
    "cookie": "^0.4.1",
    "sveltekit-i18n": "^2.0.0-rc.0"
  }

Better typescript support

Currently, there is no type checking for translation keys, which can result in typos. Also payload types have to be defined manually and options contain all definitions for all modifiers at once.

sveltekit-i18n should provide a plugin/CLI based way how to deal with that, fetching sources and generating appropriate types automatically. payload and options types should be inferred from translations dynamically according to specified key.

SEO friendlyness

Using local-router

When hitting "/" it should not redirect to "/defaultLocale" as this is not good for SEO. I believe when hitting defaultLocale it should not add "/defaultLocale" as it counts as a redirect and makes it's most of the times non-indexable.

Prepare library for contributors

Currently, the code is a bit hard to read for external contributors, so following steps need to be done:

  • Make a code revision
  • Comment functional parts
  • Create a file with contribution instructions

Log level config

In some use-cases (such as #54) would be useful to have some option to disable warnings. Currently used config.debug should be extended/replaced.

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.