i18next not working when passing multiple modules like i18next-http-backend and react-i18next and #os-team/i18next-react-native-language-detector
here is the sample code
i18n
.use(RNLanguageDetector)
.use(initReactI18next)
.use(Backend)
.init(
{
compatibilityJSON: 'v3',
fallbackLng: 'en',
supportedLngs: ['en', 'ar'],
load: 'languageOnly',
// ns: ['translations'],
// defaultNS: 'translations',
ns: ['common'],
defaultNS: 'common',
debug: true,
interpolation: {
escapeValue: false,
formatSeparator: ',',
},
react: {
useSuspense: true,
},
backend: {
crossDomain: false,
withCredentials: false,
overrideMimeType: false,
// loadPath: '${SERVER_APTH}/{{lng}}.json',
request: function (options, url, payload, callback) {
console.log('Request here to get from API');
},
reloadInterval: false,
allowMultiLoading: true,
},
initImmediate: false,
},
(error, t) => {
console.log('loading complete');
console.log('Error', error);
},
);
i18n.languages = ['en', 'ar'];
i18n.on('languageChanged', nextLng => {
console.log('Changed', nextLng);
});
Also tried with custom language detector
const languageDetector = {
type: 'languageDetector',
async: true,
detect: cb => {
console.log('Tagging here');
cb('en');
},
init: () => {},
cacheUserLanguage: () => {},
};
custom language detector work when i comment backend: { ... } section.
I need to store changed language and get translations according to it.
for changing i'm using
i18n.changeLanguage(nextLocale);
Where nextLocale will be "en" or "ar"
Related
I'm working on an app where my main window is type desktop, but opening a new window by clicking a tray opens the same index instead of opening the html file i want. If I add the file link by hardcoding it returns a white screen because vite can not complile vue and ts included in the html file.
I even added it to the input values of vite.config.js
vite.config.js
build: {
sourcemap: true,
target: `chrome${chrome}`,
outDir: 'dist',
assetsDir: '.',
rollupOptions: {
input: {
main: join(PACKAGE_ROOT, 'index.html'),
upload: './upload/upload.html', // file i want to compile with vite to make it work
},
external: [
...builtinModules.flatMap(p => [p, `node:${p}`]),
],
},
emptyOutDir: true,
brotliSize: false,
}
createSecondWindow.ts
async function createSecondWindow() {
const browserUploadWindow = new BrowserWindow({
//skipTaskbar: true,
movable: true,
roundedCorners: true,
titleBarStyle: 'default',
resizable: true,
hasShadow: true,
show: true, // Use 'ready-to-show' event to show window
height: screen.getPrimaryDisplay().size.height-300,
width: screen.getPrimaryDisplay().size.width-300,
minHeight:screen.getPrimaryDisplay().size.height-350,
minWidth:screen.getPrimaryDisplay().size.width-600,
enableLargerThanScreen: true,
webPreferences: {
nativeWindowOpen: true,
webviewTag: false,
preload: join(__dirname, '../../preload/dist/index.cjs'),
},
});
browserUploadWindow.on('ready-to-show', () => {
browserUploadWindow?.show();
if (import.meta.env.DEV) {
browserUploadWindow?.webContents.openDevTools();
}
});
const pageUrl = import.meta.env.DEV && import.meta.env.VITE_DEV_SERVER_URL !== undefined
? import.meta.env.VITE_DEV_SERVER_URL
: new URL('../renderer/dist/upload.html', 'file://' + __dirname).toString();
const uploadUrl = new URL('../renderer/upload/upload.html', 'file://' + __dirname).toString();
await browserUploadWindow.loadURL(uploadUrl);
return browserUploadWindow;
}
mainWindow.ts
async function createWindow() {
//browserWindow.setVisibleOnAllWorkspaces(true)
// let the dock be on top of the window
const browserWindow = new BrowserWindow({
type: 'desktop',
skipTaskbar: true,
roundedCorners: false,
titleBarStyle: 'hidden',
resizable: false,
hasShadow: false,
show: false, // Use 'ready-to-show' event to show window
height: screen.getPrimaryDisplay().size.height,
width: screen.getPrimaryDisplay().size.width,
enableLargerThanScreen: true,
webPreferences: {
nativeWindowOpen: true,
webviewTag: false,
preload: join(__dirname, '../../preload/dist/index.cjs'),
},
});
browserWindow.on('ready-to-show', () => {
browserWindow?.show();
if (import.meta.env.DEV) {
browserWindow?.webContents.openDevTools();
}
});
const pageUrl = import.meta.env.DEV && import.meta.env.VITE_DEV_SERVER_URL !== undefined
? import.meta.env.VITE_DEV_SERVER_URL
: new URL('../renderer/dist/index.html', 'file://' + __dirname).toString();
await browserWindow.loadURL(pageUrl);
return browserWindow;
}````
I have created Nuxt.js application, I decided to build in Nuxt/auth module, everything works fine in web browsers, but somethimes when user navigates with mobile browser my application is crushed, simply it don't respond nothing, also there is no api calls, but after one refresh everything works fine, I can not guess what's happening, I could not find anything in the resources available on the Internet.
const axios = require('axios')
export default {
// Global page headers: https://go.nuxtjs.dev/config-head
head: {
title: 'app',
htmlAttrs: {
lang: 'en'
},
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
],
script: [
// { src: "//code-eu1.jivosite.com/widget/UoBOrMfSmm", async: true },
]
},
// Global CSS: https://go.nuxtjs.dev/config-css
css: [ '~/assets/css/transition.css', '~/assets/css/errors.css' ],
pageTransition: "fade",
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [
{ src: "~/plugins/star-rating", ssr: false },
{ src: "~/plugins/mask", ssr: false },
{ src: "~/plugins/rangeSlider", ssr: false },
{ src: "~/plugins/vueSelect", ssr: false },
{ src: "~/plugins/vuelidate", ssr: false },
],
// Auto import components: https://go.nuxtjs.dev/config-components
components: true,
// Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
buildModules: [
[ '#nuxtjs/google-analytics', {
id: 'xxx'
} ]
],
// Modules: https://go.nuxtjs.dev/config-modules
modules: [
// https://go.nuxtjs.dev/bootstrap
'bootstrap-vue/nuxt',
'#nuxtjs/axios',
'#nuxtjs/toast',
'#nuxtjs/auth-next',
[ 'nuxt-lazy-load', {
defaultImage: '/spin2.gif'
} ],
[ 'nuxt-facebook-pixel-module', {
/* module options */
track: 'PageView',
pixelId: '',
autoPageView: true,
disabled: false
} ],
'nuxt-moment',
'#nuxtjs/robots',
'#nuxtjs/sitemap'
],
moment: {
locales: ['ru', 'en']
},
toast: {
position: 'top-center',
},
robots: [
{
UserAgent: '*',
Disallow: ['/user', '/admin'],
},
],
axios: {
baseURL: 'https://api.test.com/', // Used as fallback if no runtime config is provided
},
sitemap:{
exclude:[
'/user',
'/admin',
'/admin/*',
'/user/*',
],
defaults: {
changefreq: 'daily',
priority: 1,
lastmod: new Date()
},
routes: async () => {
const { data } = await axios.get('https://api.test.com/api/cars/all')
return data.map((product) => `https://test.com/product/${product.id}/${product.name}`)
}
},
loading: {
color: '#F48245',
height: '4px'
},
target: 'server',
/* auth */
auth: {
plugins:[
{ src: "~/plugins/providers", ssr:false},
],
redirect: {
login: '/',
logout: '/',
home: '/',
callback: '/callback'
},
strategies: {
local: {
token: {
property: 'user.token',
},
user: {
property: false
},
endpoints: {
login: { url: 'api/login', method: 'post' },
logout: { url: 'api/logout', method: 'post' },
user: { url: 'api/user', method: 'get' }
},
},
facebook: {
endpoints: {
userInfo: 'https://graph.facebook.com/v6.0/me?fields=id,name,picture{url}',
},
redirectUri:'xxx',
clientId: '184551510189971',
scope: ['public_profile', 'email'],
},
google: {
responseType: 'token id_token',
codeChallengeMethod: '',
clientId: 'xxx',
redirectUri: 'https://test.com/callback',
scope: ['email'],
},
},
cookie: {
prefix: 'auth.',
},
},
// Build Configuration: https://go.nuxtjs.dev/config-build
build: {},
};
This is my plugins directory file, where i am handling client oauth process.
export default async function ({ app }) {
console.log('auth executed')
if (!app.$auth.loggedIn) {
return
} else {
console.log('auth executed inside loop')
const auth = app.$auth;
const authStrategy = auth.strategy.name;
if (authStrategy === 'facebook') {
let data2 = {
fb_token: auth.user.id,
first_name: auth.user.name
}
try {
const response = await app.$axios.$post("/api/oauth", data2);
await auth.setStrategy('local');
await auth.strategy.token.set("Bearer " + response.user.token);
await auth.fetchUser();
} catch (e) {
console.log(e);
}
} else if (authStrategy === 'google') {
let dataGoogle = {
google_token: auth.user.sub,
first_name: auth.user.given_name,
last_name:auth.user.family_name
}
try {
const response = await app.$axios.$post("/api/oauth", dataGoogle);
await auth.setStrategy('local');
await auth.strategy.token.set("Bearer " + response.user.token);
await auth.fetchUser();
} catch (e) {
console.log(e);
}
}
}
}
For any issues related to DOM hydration, you can check my answer here: https://stackoverflow.com/a/67978474/8816585
It does have several possible cases (dynamic content with a difference between client side and server side rendered template, some random functions, purely wrong HTML structure etc...) and also a good blog article from Alex!
Hello guys can you help me please!
My app use up to 100% CPU when a lot of users go to my app.
I tried a lot of things, and my config turned into a mess
This is my nuxt.config.ts.
import type { NuxtConfig } from '#nuxt/types';
const isDev = process.env.NODE_ENV !== 'production';
const mainConfig: NuxtConfig = {
...
build: {
cache: true,
optimization: {
minimize: true,
runtimeChunk: true,
concatenateModules: true,
splitChunks: {
chunks: 'all',
minSize: 30000,
maxSize: 0,
minChunks: 1,
maxAsyncRequests: 20,
maxInitialRequests: 3,
automaticNameDelimiter: '~',
name: true,
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10,
chunks: 'all'
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true
}
}
}
},
filenames: {
app: ({ isDev }) => (isDev ? '[name].js' : 'js/[name]/[contenthash].js'),
chunk: ({ isDev }) => (isDev ? '[name].js' : 'js/[name]/[contenthash].js'),
css: ({ isDev }) => (isDev ? '[name].css' : 'css/[contenthash].css'),
img: ({ isDev }) => (isDev ? '[path][name].[ext]' : 'img/[contenthash:7].[ext]'),
font: ({ isDev }) => (isDev ? '[path][name].[ext]' : 'fonts/[contenthash:7].[ext]')
},
extend(config, { isClient }) {
config.externals = [
function (context, request, callback) {
if (/(pdfmake)/.test(request) || /(xlsx)/.test(request)) {
return callback(null, 'commonjs ' + request);
}
callback();
}
];
}
},
router: { ... },
modules: [ ... ],
server: { ... },
watchers: {
webpack: {
ignored: ['**/node_modules', 'node_modules']
}
}
};
export default mainConfig;
The application does not stand up to 2000 users and breaks,
I really dont know what to do! :(
Maybe you will can help me?
I'm trying to add a element to a array, which is called allLogbooks. This array contains objects called Logbook. My issue is, how do I fit in code so that it adds the new element to the array which is declared in my reducer? This is my initial state:
const initialState = {
isFetching: false,
error: undefined,
isRegistered: false,
isUpdated: false,
hasChecked: false,
isError: false,
registerStepOne: true,
registerStepTwo: false,
registerStepThree: false,
registerStepFour: false,
logbooks: undefined,
allLogbooks: [],
userInfo: undefined,
logbookAddSuccess: false,
newLogbook: undefined,
graphFilter: 1
}
This is my reducer:
case ADD_LOGBOOK_SUCCESS:
allLogbooks.push(action.newLogbook);
return {
...state,
isFetching: false,
logbookAddSuccess: true,
isUpdated: true,
isError: false,
}
And this is my action:
function addLogbookSuccess(newLogbook) {
return {
type: ADD_LOGBOOK_SUCCESS
}
}
I then make a POST call to a nodejs server, where it will respond with a message if it was successful, and the logbook which was just created. the following data is what it returns:
{
"success": true,
"logbook": {
"created_by": "",
"created_at": "",
"_id": "",
"__v": 0
}
}
I then dispatch in the API call, as such:
.then(data => data.json())
.then(json => {
Keyboard.dismiss();
dispatch(addLogbookSuccess(json.logbook));
})
.catch(err => dispatch(addLogbookFailed(err)))
I've substituted this by using AsyncStorage to access the array abroad all my views, but I know this is wrong.
I am struggling a little to comprehend your question so I've tried my best. Please let me know if I'm completely off with my answer.
Your reducer:
case ADD_LOGBOOK_SUCCESS: {
const newLogbook = action.payload;
return {
...state,
isFetching: false,
logbookAddSuccess: true,
isUpdated: true,
isError: false,
allLogBooks: [
...state.allLogBooks,
newLogbook
]
}
}
Your action:
function addLogbookSuccess(newLogbook) {
return {
type: ADD_LOGBOOK_SUCCESS,
payload: newLogbook
}
}
I am trying to setup Karma with Jasmine for testing my Angular2 app. Karma fails to append extensions for imports in spec files. For example my spec file has import {TileComponent} from './tiles.component';
When I run Karma I get the following error: http://localhost:9876/base/wwwroot/app/tiles/tiles.component 404 (Not Found)
If I try to go to this link and manually apend js at the end it will load my file.
karma.conf.js:
module.exports = function (config) {
var appBase = 'wwwroot/app/';
var appAssets = '/base/app/';
config.set({
basePath: '',
frameworks: ['jasmine'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-htmlfile-reporter')
],
customLaunchers: {
Chrome_travis_ci: {
base: 'Chrome',
flags: ['--no-sandbox']
}
},
files: [ 'node_modules/systemjs/dist/system.src.js',
'node_modules/core-js/client/shim.js',
'node_modules/reflect-metadata/Reflect.js',
'node_modules/zone.js/dist/zone.js',
'node_modules/zone.js/dist/jasmine-patch.js',
'node_modules/zone.js/dist/async-test.js',
'node_modules/zone.js/dist/fake-async-test.js',
// RxJs.
{ pattern: 'node_modules/rxjs/**/*.js', included: false, watched: false },
{ pattern: 'node_modules/rxjs/**/*.js.map', included: false, watched: false },
{ pattern: 'node_modules/#angular/**/*.js', included: false, watched: false },
{ pattern: 'node_modules/#angular/**/*.js.map', included: false, watched: false },
{ pattern: 'systemjs.config.js', included: false, watched: false },
//{ pattern: 'karma-test-shim.js', included: false, watched: false },
//'systemjs.config.js',
'karma-test-shim.js',
{ pattern: appBase + '**/*.js', included: false, watched: true },
{ pattern: appBase + '**/*.html', included: false, watched: true },
{ pattern: 'wwwroot/styles/**/*.css', included: false, watched: true },
{ pattern: 'app/**/*.ts', included: false, watched: false },
{ pattern: appBase + '**/*.js.map', included: false, watched: false }
],
proxies: {
"/app/": appAssets
},
exclude: [],
preprocessors: {},
reporters: ['progress', 'html'],
htmlReporter: {
outputFile: '_test-output/tests.html',
pageTitle: 'Unit Tests',
subPageTitle: __dirname
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
})
}
karma-test-shim.js
// /*global jasmine, __karma__, window*/
Error.stackTraceLimit = Infinity;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;
__karma__.loaded = function () {
};
function isJsFile(path) {
return path.slice(-3) === '.js';
}
function isSpecFile(path) {
return /\.spec\.js$/.test(path);
}
function isBuiltFile(path) {
var builtPath = '/base/wwwroot/';
return isJsFile(path) && (path.substr(0, builtPath.length) === builtPath);
}
var allSpecFiles = Object.keys(window.__karma__.files)
.filter(isSpecFile)
.filter(isBuiltFile);
System.config({
baseURL: '/base',
packageWithIndex: true, // sadly, we can't use umd packages (yet?)
map: {
'http://localhost:9876/base/wwwroot/app/app.component': 'http://localhost:9876/base/wwwroot/app/app.component.js'
}
});
System.import('systemjs.config.js')
.then(function () {
return Promise.all([
System.import('#angular/core/testing'),
System.import('#angular/platform-browser-dynamic/testing')
])
})
.then(function (providers) {
var testing = providers[0];
var testingBrowser = providers[1];
testing.setBaseTestProviders(
testingBrowser.TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS,
testingBrowser.TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS);
})
.then(function () {
// Finally, load all spec files.
// This will run the tests directly.
return Promise.all(
allSpecFiles.map(function (moduleName) {
return System.import(moduleName);
}));
})
.then(__karma__.start, __karma__.error);
The problem was that I was importing system.config.js twice. I removed import from karma.conf.js file.
I also did some minor path changes.