Skip to content

Commit

Permalink
feat: allow passing functions to i18next init
Browse files Browse the repository at this point in the history
  • Loading branch information
blarfoon authored and yassinedoghri committed Jun 12, 2022
1 parent 2d30fae commit ed7c721
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/index.mts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { AstroIntegration } from "astro";
import { InitOptions, Resource } from "i18next";
import * as fs from "fs";
import * as path from "path";
import { deeplyStringifyObject } from "./utils";

interface AstroI18nextOptions {
resourcesPath?: string;
Expand Down Expand Up @@ -52,7 +53,7 @@ export default (options: AstroI18nextOptions): AstroIntegration => {
injectScript(
"page-ssr",
`import i18next from "i18next";
i18next.init(${JSON.stringify(options.i18next)});`
i18next.init(${deeplyStringifyObject(options.i18next)});`
);
},
},
Expand Down
38 changes: 38 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,3 +104,41 @@ export const localizePath = (

return "/" + pathSegments.join("/");
};

export const deeplyStringifyObject = (obj: object | Array<any>) => {
const isArr = Array.isArray(obj);
let str = isArr ? "[" : "{";
for (const key in obj) {
if (obj[key] === null || obj[key] === undefined) {
continue;
}
let val = null;
switch (typeof obj[key]) {
case "string": {
val = `"${obj[key]}"`;
break;
}
case "number":
case "boolean": {
val = obj[key];
break;
}
case "object": {
val = deeplyStringifyObject(obj[key]);
break;
}
case "function": {
val = obj[key].toString();
break;
}
case "symbol": {
val = `Symbol("${obj[key].description}")`;
break;
}
default:
break;
}
str += isArr ? `${val},` : `"${key}": ${val},`;
}
return `${str}${isArr ? "]" : "}"}`;
};

0 comments on commit ed7c721

Please sign in to comment.