i18next - " WebpackError: TypeError: namespaces.forEach is not a function" (hooks)
i18next - " WebpackError: TypeError: namespaces.forEach is not a function" (hooks)
我试图让 i18next
在我的 Gatsby 项目中工作,但每当我尝试使用 yarn build
.[=20= 进行构建时,我都会将 运行 保持在以下错误中]
来自我的 package.json
:
"i18next": "^19.8.2",
"react-i18next": "^11.7.3",
我的 i18n/index.js
文件:
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
// ...
i18n.use(initReactI18next).init({
fallbackLng: "en",
// have a common namespace used around the full app
ns: ["translations"],
defaultNS: "translations",
wait: true,
useSuspense: false
}, (err, t) => {
i18n.t('en');
});
// load additional namespaces after initialization
i18n.loadNamespaces('translations', (err, t) => {
i18n.t('i18n', { lng: 'en' } );
});
// i18n resource bundles for views
const i18nResourceBundlesViews = [
{
intro: {
en: { ...intro.en },
ja: { ...intro.ja },
},
},
// ...
];
// i18n resource bundles for components
const i18nResourceBundlesComponents = [
{
header: {
en: { ...header.en },
ja: { ...header.ja },
},
},
{
footer: {
en: { ...footer.en },
ja: { ...footer.ja },
},
},
];
// Load i18n resource bundles from each resource object
const getI18nResourceBundles = (resource) => {
const key = Object.keys(resource)[0];
const enBundle = resource[key].en;
const jaBundle = resource[key].ja;
// English translations
i18n.addResourceBundle('en', key, enBundle);
// Japanese translations
i18n.addResourceBundle('ja', key, jaBundle);
};
// i18n resource bundles for views
i18nResourceBundlesViews.forEach((resource) => {
getI18nResourceBundles(resource);
});
// i18n resource bundles for components
i18nResourceBundlesComponents.forEach((resource) => {
getI18nResourceBundles(resource);
});
export default i18n;
yarn build
后的完整错误信息
❯ yarn build
yarn run v1.22.5
$ gatsby build
success open and validate gatsby-configs - 0.044s
success load plugins - 0.800s
success onPreInit - 0.016s
success delete html and css files from previous builds - 0.027s
success initialize cache - 0.009s
success copy gatsby files - 0.154s
success onPreBootstrap - 0.020s
success createSchemaCustomization - 0.007s
success source and transform nodes - 1.225s
success building schema - 0.415s
success createPages - 0.021s
success createPagesStatefully - 0.104s
success onPreExtractQueries - 0.002s
success update schema - 0.052s
success extract queries from components - 0.418s
success write out requires - 0.008s
success write out redirect data - 0.005s
warn The icon(./static/favicon/favicon-512.png) you provided to 'gatsby-plugin-manifest' is not square.
The icons we generate will be square and for the best results we recommend you provide a square icon.
success Build manifest and related icons - 0.183s
success onPostBootstrap - 0.192s
⠀
info bootstrap finished - 6.260 s
⠀
warn Browserslist: caniuse-lite is outdated. Please run:
npx browserslist@latest --update-db
success Building production JavaScript and CSS bundles - 19.520s
success Rewriting compilation hashes - 0.010s
success run queries - 20.490s - 6/6 0.29/s
failed Building static HTML for pages - 4.770s
ERROR #95313
Building static HTML failed for path "/404/"
See our docs page for more info on this error: https://gatsby.dev/debug-html
37 | var _this = this;
38 |
> 39 | namespaces.forEach(function (ns) {
| ^
40 | if (!_this.usedNamespaces[ns]) _this.usedNamespaces[ns] = true;
41 | });
42 | }
WebpackError: TypeError: namespaces.forEach is not a function
- context.js:39 ReportNamespaces.addUsedNamespaces
node_modules/react-i18next/dist/es/context.js:39:1
- useTranslation.js:41 useTranslation
node_modules/react-i18next/dist/es/useTranslation.js:41:1
- index.jsx:27 Footer
src/components/theme/Footer/index.jsx:27:38
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
在我的Footer/index.jsx
最初发生错误的地方(第27行):
const { t, i18n } = useTranslation({useSuspense: false});
如有任何帮助,我们将不胜感激。谢谢
此问题已解决。
包含解决方案的参考:https://github.com/benji011/portfolio.benjaminlo.io/pull/9#issuecomment-707612060
I think I've managed to pinpoint the two issues you were originally
having. I've uploaded the fixes I've made, please see if it builds for
you. It builds fine for me.
1. React suspense:
i18n appears to use Suspense but this is problematic for Gatsby. See
here.
The fix is quite straightforward and I've added it to the config.
2. The i18ncheck
statement: ```const i18nCheck = i18n.languages.toLowerCase().includes('en') ||
i18n.languages.toLowerCase().includes('en-');```
This statement is problematic.
There are two variables that contain the languages.
language
, which I think is the current language, and is set to a string: en
languages
which is an array of languages. This is set to ['en', 'dev']
.
If you want to check for the array languages
, then we can't use
toLowerCase()
like it was used. It will result in an error as we are
applying toLowerCase()
on the entire array and not an element of the
array. toLowerCase()
must be used on a string and won't ork on an
array. We would have to loop through the array and then apply
toLowerCase()
. I don't think you were wanting to check the array
though as the language, for example 'en', would always be in the
array.
Another issue related to this is that i18n
might not have the
property yet, so we need to check that it has the property first.
The best approach, imo, is to just check the language
to see if it
is en
or en-
.
Regarding ESLint and Prettier:
You should use both.
ESLint is a linter and will show code errors. The project already has
an ESLint config, you just need the plugin. There might be a window
that pops up when you open the project, which you must then choose
Allow
.
Prettier is a formatter and will format your code e.g. split up a long
line into 3 separate lines
我试图让 i18next
在我的 Gatsby 项目中工作,但每当我尝试使用 yarn build
.[=20= 进行构建时,我都会将 运行 保持在以下错误中]
来自我的 package.json
:
"i18next": "^19.8.2",
"react-i18next": "^11.7.3",
我的 i18n/index.js
文件:
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
// ...
i18n.use(initReactI18next).init({
fallbackLng: "en",
// have a common namespace used around the full app
ns: ["translations"],
defaultNS: "translations",
wait: true,
useSuspense: false
}, (err, t) => {
i18n.t('en');
});
// load additional namespaces after initialization
i18n.loadNamespaces('translations', (err, t) => {
i18n.t('i18n', { lng: 'en' } );
});
// i18n resource bundles for views
const i18nResourceBundlesViews = [
{
intro: {
en: { ...intro.en },
ja: { ...intro.ja },
},
},
// ...
];
// i18n resource bundles for components
const i18nResourceBundlesComponents = [
{
header: {
en: { ...header.en },
ja: { ...header.ja },
},
},
{
footer: {
en: { ...footer.en },
ja: { ...footer.ja },
},
},
];
// Load i18n resource bundles from each resource object
const getI18nResourceBundles = (resource) => {
const key = Object.keys(resource)[0];
const enBundle = resource[key].en;
const jaBundle = resource[key].ja;
// English translations
i18n.addResourceBundle('en', key, enBundle);
// Japanese translations
i18n.addResourceBundle('ja', key, jaBundle);
};
// i18n resource bundles for views
i18nResourceBundlesViews.forEach((resource) => {
getI18nResourceBundles(resource);
});
// i18n resource bundles for components
i18nResourceBundlesComponents.forEach((resource) => {
getI18nResourceBundles(resource);
});
export default i18n;
yarn build
❯ yarn build
yarn run v1.22.5
$ gatsby build
success open and validate gatsby-configs - 0.044s
success load plugins - 0.800s
success onPreInit - 0.016s
success delete html and css files from previous builds - 0.027s
success initialize cache - 0.009s
success copy gatsby files - 0.154s
success onPreBootstrap - 0.020s
success createSchemaCustomization - 0.007s
success source and transform nodes - 1.225s
success building schema - 0.415s
success createPages - 0.021s
success createPagesStatefully - 0.104s
success onPreExtractQueries - 0.002s
success update schema - 0.052s
success extract queries from components - 0.418s
success write out requires - 0.008s
success write out redirect data - 0.005s
warn The icon(./static/favicon/favicon-512.png) you provided to 'gatsby-plugin-manifest' is not square.
The icons we generate will be square and for the best results we recommend you provide a square icon.
success Build manifest and related icons - 0.183s
success onPostBootstrap - 0.192s
⠀
info bootstrap finished - 6.260 s
⠀
warn Browserslist: caniuse-lite is outdated. Please run:
npx browserslist@latest --update-db
success Building production JavaScript and CSS bundles - 19.520s
success Rewriting compilation hashes - 0.010s
success run queries - 20.490s - 6/6 0.29/s
failed Building static HTML for pages - 4.770s
ERROR #95313
Building static HTML failed for path "/404/"
See our docs page for more info on this error: https://gatsby.dev/debug-html
37 | var _this = this;
38 |
> 39 | namespaces.forEach(function (ns) {
| ^
40 | if (!_this.usedNamespaces[ns]) _this.usedNamespaces[ns] = true;
41 | });
42 | }
WebpackError: TypeError: namespaces.forEach is not a function
- context.js:39 ReportNamespaces.addUsedNamespaces
node_modules/react-i18next/dist/es/context.js:39:1
- useTranslation.js:41 useTranslation
node_modules/react-i18next/dist/es/useTranslation.js:41:1
- index.jsx:27 Footer
src/components/theme/Footer/index.jsx:27:38
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
在我的Footer/index.jsx
最初发生错误的地方(第27行):
const { t, i18n } = useTranslation({useSuspense: false});
如有任何帮助,我们将不胜感激。谢谢
此问题已解决。
包含解决方案的参考:https://github.com/benji011/portfolio.benjaminlo.io/pull/9#issuecomment-707612060
I think I've managed to pinpoint the two issues you were originally having. I've uploaded the fixes I've made, please see if it builds for you. It builds fine for me.
1. React suspense:
i18n appears to use Suspense but this is problematic for Gatsby. See here.
The fix is quite straightforward and I've added it to the config.
2. The
i18ncheck
statement: ```const i18nCheck = i18n.languages.toLowerCase().includes('en') ||i18n.languages.toLowerCase().includes('en-');```
This statement is problematic.
There are two variables that contain the languages.
language
, which I think is the current language, and is set to a string:en
languages
which is an array of languages. This is set to['en', 'dev']
.If you want to check for the array
languages
, then we can't usetoLowerCase()
like it was used. It will result in an error as we are applyingtoLowerCase()
on the entire array and not an element of the array.toLowerCase()
must be used on a string and won't ork on an array. We would have to loop through the array and then applytoLowerCase()
. I don't think you were wanting to check the array though as the language, for example 'en', would always be in the array.Another issue related to this is that
i18n
might not have the property yet, so we need to check that it has the property first.The best approach, imo, is to just check the
language
to see if it isen
oren-
.Regarding ESLint and Prettier:
You should use both.
ESLint is a linter and will show code errors. The project already has an ESLint config, you just need the plugin. There might be a window that pops up when you open the project, which you must then choose
Allow
.Prettier is a formatter and will format your code e.g. split up a long line into 3 separate lines