declaring namespacesRequired array on page-level component - internationalization

I've got a project based on next and react, using i18next package I encounter the following warning which I think is the reason why it takes plenty of time to load i18n according to react profiler:
You have not declared a namespacesRequired array on your page-level
component: withI18nextTranslation(Error). This will cause all
namespaces to be sent down to the client, possibly negatively
impacting the performance of your app. For more info, see:
https://github.com/isaachinman/next-i18next#4-declaring-namespace-dependencies
notes : The translation works fine, I have declared namespacesRequierd in all of my components except 404.
this is my i18n config :
const NextI18Next = require('next-i18next').default
const { localeSubpaths } = require('next/config').default().publicRuntimeConfig
const path = require('path');
module.exports = new NextI18Next({
preload: ['fa'],
defaultLanguage: 'fa',
otherLanguages: ['en','ar'],
localeSubpaths,
localePath: path.resolve('./public/static/locales'),
localeStructure: '{{lng}}/{{ns}}',
fallbackLng: 'fa',
ignoreRoutes:['/_next/', '/static/', '/public/', '/api/'],
serverLanguageDetection: false,
defaultNS: 'common',
localeExtension: 'json'
});
next.config.js :
const { nextI18NextRewrites } = require('next-i18next/rewrites');
rewrites: async () => nextI18NextRewrites(localeSubpaths),
publicRuntimeConfig: {
localeSubpaths
}
versions :
package.json :
"i18next": "^19.7.0"
yarn :
next-i18next#^6.0.2:
version "6.0.2"
dependencies:
"#types/express" "^4.16.1"
core-js "^3"
hoist-non-react-statics "^3.2.0"
i18next "^19.6.3"
i18next-browser-languagedetector "^5.0.0"
i18next-fs-backend "^1.0.7"
i18next-http-backend "^1.0.17"
i18next-http-middleware "^3.0.2"
path-match "^1.2.4"
prop-types "^15.6.2"
react-i18next "^11.7.0"
url "^0.11.0"
there's nothing related to this in my server.js file.

Related

How to combine withPlugins with internatioinalization config in a next.config.js file

I have the following code in my next.config.js
const withPlugins = require('next-compose-plugins');
const optimizedImages = require('next-optimized-images');
module.exports = withPlugins([optimizedImages], { target: 'serverless' });
and now I need to add the following config to the file, combining with the plugin
i18n: {
locales: ["en", "es"],
defaultLocale: "en",
},
I have tried the following,
const nextConfig = {
i18n: {
locales: ["en", "es"],
defaultLocale: "en",
},
};
module.exports = withPlugins([
[optimizedImages, {
target: 'serverless'
},
],
nextConfig,
])
and restarted the server, but I have not been successful ...
What version of Next.JS are you using? I faced the same problem and it was fixed by updating to +10.0.0.
You can see on the i18n documentation on Next that this is the minimum version.
Next.js has built-in support for internationalized (i18n) routing since v10.0.0. You can provide a list of locales, the default locale, and domain-specific locales and Next.js will automatically handle the routing.
More info: https://nextjs.org/docs/advanced-features/i18n-routing

ERR_TOO_MANY_REDIRECTS on vercel after deploying Nextjs App

I deployed my nextjs app to Vercel and it was a success.
I can see a preview of the website and even the log saying it works well.
But i try to access the website via the default Vercel domain :
https://tly-nextjs.vercel.app/
I get an ERR_TOO_MANY_REDIRECTS.
I do not have this problem locally.
I tried :
Disabling a language redirect that I use (/en for english folks, and / for french people).
Disabling the language detector of i18next.
But none of these solutions changed anything.
Any ideas ?
i18n.js file
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import Cache from 'i18next-localstorage-cache';
import LanguageDetector from 'i18next-browser-languagedetector';
const fallbackLng = ['fr'];
const availableLanguages = ['fr', 'en'];
const en = require('./locales/en/common.json');
const fr = require('./locales/fr/common.json');
const options = {
order: ['querystring', 'navigator'],
lookupQuerystring: 'lng'
}
const cacheOptions = {
// turn on or off
enabled: true,
// prefix for stored languages
prefix: 'i18next_res_',
// expiration
expirationTime: 365*24*60*60*1000,
// language versions
//versions: {}
}
i18n
.use(Cache)
.use(initReactI18next)
.use(LanguageDetector)
.init({
cache: cacheOptions,
fallbackLng: fallbackLng,
debug: true,
detection: options,
supportedLngs: availableLanguages,
nonExplicitSupportedLngs: true,
resources: {
en: {translation: en},
fr: {translation: fr},
},
interpolation: {
escapeValue: false,
},
react: {
wait: true,
useSuspense: true,
},
});
export default i18n;
My change Language function :
const changeLanguageInHouse = (lang, bool) => {
setLoading(true);
i18next.changeLanguage(lang).then((t) => {
setLanguage(lang);
bake_cookie("langChoice", lang);
setLoading(false);
if (bool === true) {
var newUrl2 = (lang === "fr" ? "" : "/en") + asPath;
window.location.replace(newUrl2);
}
});
};
What happend at your server is following:
You enter https://tly-nextjs.vercel.app/ and it is redirected to /en with HTTP-Status-Code 307 (Temporary Redirect).
And /en redirect with 301 (Permanent Redirect) to /.
You can reproduce this by open the Browser-Dev-Tools and have a look at the Network Tab.
It might be, that you have some kind of url-rewriting activated at your server, which redirect everything to your domain-root.
Is there a public repo available for this? Here is how it worked for me.
Try changing the order of the locales and the default locale (not sure this helps, but it changed something for me. Undocumented if that is the case!)
So I put the default locale first (which is nl for me) in both the locales array and the domains array.
Let me know if that helps!
module.exports = {
i18n: {
localeDetection: false,
// These are all the locales you want to support in
// your application
locales: ['nl', 'en'],
// This is the default locale you want to be used when visiting
// a non-locale prefixed path e.g. `/hello`
defaultLocale: 'nl',
// This is a list of locale domains and the default locale they
// should handle (these are only required when setting up domain routing)
domains: [
{
domain: 'example.be',
defaultLocale: 'nl',
},
{
domain: 'example.com',
defaultLocale: 'en',
},
],
},
trailingSlash: true,
};
I changed all my getInitialProps to getServerSideProps
and realised I was doing a redirect on response :
res.writeHead(301, { Location: "/" })
I just delete it.
And now I don't have this endless redirect.
Doing this worked for me...
https://ardasevinc.tech/cloudflare-vercel-too-many-redirects
I think it's the actual solution to the cause of the problem rather than a bandage!

Unresolved dependencies & Missing global variable name when trying to import #mapbox/mapbox-gl-geocoder

I'm beginning with Svelte and I would like to (more or less) reproduce Mapbox store locator tutorial with Svelte & rollup. (Starting from svelte REPL starter kit).
Everything's fine for loading a map and some markers, but as soon as I try to import this package https://github.com/mapbox/mapbox-gl-geocoder, nothing works anymore and I'm not familiar enough with Svelte to figure out how to setup rollup and fix it.
<script>
import { onMount, setContext } from 'svelte'
import mapbox from 'mapbox-gl/dist/mapbox-gl.js';
import MapboxGeocoder from '#mapbox/mapbox-gl-geocoder'; // <<--- Problem here
mapbox.accessToken = 'xxx';
let map;
let geocoder;
onMount(() => {
map = new mapbox.Map({,,,});
geocoder = new MapboxGeocoder({,,,});
});
</script>
terminal :
bundles src/main.js → public/build/bundle.js...
(!) Missing shims for Node.js built-ins
Creating a browser bundle that depends on 'events'. You might need to include https://github.com/ionic-team/rollup-plugin-node-polyfills
(!) Unresolved dependencies
https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency
events (imported by node_modules/#mapbox/mapbox-gl-geocoder/lib/index.js, events?commonjs-external)
(!) Missing global variable name
Use output.globals to specify browser global variable names corresponding to external modules
events (guessing 'events$1')
created public/build/bundle.js in 2s
browser console :
Uncaught ReferenceError: events$1 is not defined
at main.js:5
Then, I tried to add to my rollup config resolve and polyfills plugins, but have other errors.
rollup.config.js
import svelte from 'rollup-plugin-svelte';
import resolve from '#rollup/plugin-node-resolve';
import commonjs from '#rollup/plugin-commonjs';
import livereload from 'rollup-plugin-livereload';
import { terser } from 'rollup-plugin-terser';
import preprocess from 'svelte-preprocess';
import nodeResolve from '#rollup/plugin-node-resolve';
import nodePolyfills from 'rollup-plugin-node-polyfills';
const production = !process.env.ROLLUP_WATCH;
export default {
input: 'src/main.js',
output: {
sourcemap: true,
format: 'iife',
name: 'app',
file: 'public/build/bundle.js'
},
plugins: [
nodeResolve(),
nodePolyfills(),
svelte({
// enable run-time checks when not in production
dev: !production,
// we'll extract any component CSS out into
// a separate file - better for performance
css: css => {
css.write('bundle.css');
},
preprocess: preprocess()
}),
// If you have external dependencies installed from
// npm, you'll most likely need these plugins. In
// some cases you'll need additional configuration -
// consult the documentation for details:
// https://github.com/rollup/plugins/tree/master/packages/commonjs
resolve({
browser: true,
dedupe: ['svelte']
}),
commonjs(),
// In dev mode, call `npm run start` once
// the bundle has been generated
!production && serve(),
// Watch the `public` directory and refresh the
// browser on changes when not in production
!production && livereload('public'),
// If we're building for production (npm run build
// instead of npm run dev), minify
production && terser()
],
watch: {
clearScreen: false
}
};
function serve() {
let started = false;
return {
writeBundle() {
if (!started) {
started = true;
require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {
stdio: ['ignore', 'inherit', 'inherit'],
shell: true
});
}
}
};
}
Gives me this
bundles src/main.js → public/build/bundle.js...
LiveReload enabled
(!) `this` has been rewritten to `undefined`
https://rollupjs.org/guide/en/#error-this-is-undefined
node_modules/base-64/base64.js
163: }
164:
165: }(this));
^
to conclude: I'm a bit lost :D
thanks in advance

Integrating D3 with Angular-cli

I am trying to integrate D3 chart library with Angular CLI. First I installed d3 with npm install d3 --save. Once done my node_modules looks like
d3 version is "d3": "^4.2.2".
Then I set up configuration as below.
angular-cli-build.js
var Angular2App = require('angular-cli/lib/broccoli/angular2-app');
module.exports = function(defaults) {
return new Angular2App(defaults, {
vendorNpmFiles: [
......
'd3/**/*'
]
});
};
system-config.ts
"use strict";
// SystemJS configuration file, see links for more information
// https://github.com/systemjs/systemjs
// https://github.com/systemjs/systemjs/blob/master/docs/config-api.md
/***********************************************************************************************
* User Configuration.
**********************************************************************************************/
/** Map relative paths to URLs. */
const map:any = {
'#angular2-material': 'vendor/#angular2-material',
// 'd3': 'vendor/d3'
'd3': 'vendor/d3/build'
};
/** User packages configuration. */
const materialPackages:string[] = [
'core',
'button',
'icon',
'sidenav',
'toolbar',
'list',
'card'
];
const packages:any = {
'd3': {
format: 'cjs',
defaultExtension: 'js',
main: 'd3'
},
};
materialPackages.forEach(name => {
packages[`#angular2-material/${name}`] = {
format: 'cjs',
defaultExtension: 'js',
main: name
};
});
////////////////////////////////////////////////////////////////////////////////////////////////
/***********************************************************************************************
* Everything underneath this line is managed by the CLI.
**********************************************************************************************/
const barrels:string[] = [
// Angular specific barrels.
'#angular/core',
'#angular/common',
'#angular/compiler',
'#angular/forms',
'#angular/http',
'#angular/router',
'#angular/platform-browser',
'#angular/platform-browser-dynamic',
// Thirdparty barrels.
'rxjs',
// App specific barrels.
'app',
'app/shared',
'app/bar',
'app/chart',
/** #cli-barrel */
];
const cliSystemConfigPackages:any = {};
barrels.forEach((barrelName:string) => {
cliSystemConfigPackages[barrelName] = {main: 'index'};
});
/** Type declaration for ambient System. */
declare var System:any;
// Apply the CLI SystemJS configuration.
System.config({
map: {
'#angular': 'vendor/#angular',
'rxjs': 'vendor/rxjs',
'main': 'main.js',
},
packages: cliSystemConfigPackages
});
// Apply the user's configuration.
System.config({map, packages});
In app.module.ts, I imported d3 as below.
import * as d3 from 'd3';
Then,
#NgModule({
declarations: [AppComponent, d3],
providers: [],
imports: [],
bootstrap: [AppComponent],
})
Following is what my dist folder looks,
When I try to build the project with ng build it gives below error.
Cannot find module 'd3'
Any suggestions are highly appreciated.
Thank You
You should try to add d3 typings to your project, d3 does not include typings and you have to get it to use the import system.
You can :
use the TypeScript Definition Manager in order to import the requested typing in your project :
typings install dt~d3 --global --save
Then you will have the definition file for d3 in your typings directory.
Refers to angular-cli, you can install typings by using npm :
npm install #types/d3 --save-dev
After all, you should take a look to the d3 definition file to be sure that is the correct typing for the latest release of d3.

CanJS with StealJS 0.3.0

I am playing around on an app with canjs 2.1.0 and stealjs 0.3.0:
I have stealconfig.js like below:
System.config({
map: {
"can/util/util": "can/util/jquery/jquery",
"jquery/jquery": "jquery"
},
paths: {
"jquery": "bower_components/jquery/dist/jquery.js",
"can/*": "bower_components/canjs/*.js",
"lodash": "bower_components/lodash/dist/lodash.js",
"bootstrap" : "bower_components/bootstrap/dist/js/bootstrap.js",
"bootstrap.css" : "bower_components/bootstrap/dist/css/bootstrap.csscss"
},
meta: {
jquery: {
exports: "jQuery",
deps: supportsUnknownElements ? undefined : ["can/lib/html5shiv.js"]
}
},
ext: {
mustache: "can/view/mustache/system"
}
});
And my main.js is:
import can from 'can/';
import $ from 'jquery';
import _ from 'lodash';
import LayoutController from 'apps/layout/layout';
can.route.ready();
new LayoutController(document.body, {});
layout .js loos like:
(function() {
'use strict';
var can = require('can/'),
layoutView = require('./view/layout.mustache!');
})();
But, I get these errors.
GET http://localhost:8080/bower_components/canjs/can.js 404 (Not Found)
GET http://localhost:8080/bower_components/canjs/view/mustache/system.js 404 (Not Found)
How can I solve this issue?
To use CanJS with the new Steal you need to be using the minor branch of CanJS. There hasn't been a tag release yet that supports the new version of Steal.
You can do this easily with bower, just like this (in your dependencies):
"canjs": "bitovi/canjs#minor"
Other comments:
1) When you're using CommonJS (as you are in layout.js) you don't need to wrap it in an self-calling function. That will be done by Steal.
2) The error suggests it cannot find the file. Are you certain you have ran "bower install" to install CanJS? Your configuration looks fine.

Resources