Configure i18next to use warning logs instead of default info level - javascript

Currently I have many logs by i18next that make difficult to use the console:
I need i18next to use warning level instead of default info level, in order to be able to filter them.
Im checking docs but I dont see any option. My current configuration is:
i18n
.use(XHR)
.use(LanguageDetector)
.init({
debug: true,
lng: 'en',
keySeparator: false,
addMissing: true,
interpolation: {
escapeValue: false
},
resources: {
en: {
translations: translationEng
},
ns: ['translations'],
defaultNS: 'translations'
})

You can disable debug: false, which will disable the default console.log stuff.
And and an event listener missingKey on the i18n instance.
i18n
.use(XHR)
.use(LanguageDetector)
.init({
debug: false, // <-- disable default console.log
lng: 'en',
keySeparator: false,
addMissing: true,
interpolation: {
escapeValue: false
},
resources: {
en: {
translations: translationEng
},
ns: ['translations'],
defaultNS: 'translations'
});
i18n.on('missingKey', (lng, namespace, key, fallbackValue) => {
console.warn(lng, namespace, key, fallbackValue);
})
Based on this code
Other option is to use the options.missingKeyHandler to pass a custom handler for handing missing keys.
i18n
.use(XHR)
.use(LanguageDetector)
.init({
debug: false, // disable this
lng: 'en',
keySeparator: false,
addMissing: true,
interpolation: {
escapeValue: false
},
resources: {
en: {
translations: translationEng
},
ns: ['translations'],
defaultNS: 'translations',
saveMissing: true, // must be enabled
missingKeyHandler: (lng, ns, key, fallbackValue) => {
console.warn(lng, ns, key, fallbackValue)
}
})
Based on this code

Related

Nuxt/ESLint - Parsing error: Must use import to load ES Module

I am using Nuxt 2.15.7 in VS Code, using Node version 14.17.1 and the eslint extension.
The problem
I started seeing a red squiggly line under the 1st character of every file. When hovering over it, this is the error I see:
require() of ES modules is not supported.
require() of C:\Users\SR Gears\Documents\work\my-website\node_modules\eslint\node_modules\eslint-scope\lib\definition.js
from C:\Users\SR Gears\Documents\work\my-website\node_modules\babel-eslint\lib\require-from-eslint.js
is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename definition.js to end in .cjs,
change the requiring code to use import(),
or remove "type": "module" from
C:\Users\SR Gears\Documents\work\my-website\node_modules\eslint\node_modules\eslint-scope\package.json.eslint
What I have tried so far
First, I tried renaming the appropriate files as listed above in the error, and restarting the eslint server, but the error remains.
So, I went over to the eslint extension in VS Code and read the following:
The approval flow to allow the execution of a ESLint library got reworked. Its initial experience is now as follows:
- no modal dialog is shown when the ESLint extension tries to load an ESLint library for the first time and an approval is necessary. Instead the ESLint status bar item changes to ESLint status icon indicating that the execution is currently block.
- if the active text editor content would be validated using ESLint, a problem at the top of the file is shown in addition.
The execution of the ESLint library can be denied or approved using the following gestures:
- clicking on the status bar icon
- using the quick fix for the corresponding ESLint problem
- executing the command ESLint: Manage Library Execution from the command palette
Okay, so I tried the above suggestions:
clicking on the status bar icon (it isn't there in my status bar)
using the quick fix for the corresponding ESLint problem (shows no quick fix available)
executing the command ESLint: Manage Library Execution from the command palette (I get a message that this request is unknown)
Potential Fix with error
So, I navigated over to eslintrc.js I hovered over module.exports = { on line 1, and got the lightbulb icon show. The Quick Fix says Convert to ES6 module. When I click this, the file is updated. All variable keys within the options are updated to have export in front of them. This does remove the error line at the top of the files, but gives a new error for export const extends: [] variable:
'extends' is not allowed as a variable declaration name.. My eslintrc.js file (before updating to ES6 module) is here:
eslintrc.js
module.exports = {
root: true,
env: {
browser: true,
node: true
},
parserOptions: {
parser: 'babel-eslint'
},
extends: [
'plugin:nuxt/recommended',
'plugin:vue/recommended',
'eslint:recommended',
// 'prettier/vue',
'plugin:prettier/recommended'
],
globals: {
$nuxt: true,
page: true,
browser: true,
context: true,
jestPuppeteer: true
},
plugins: ['nuxt', 'vue', 'prettier'],
rules: {
'new-cap': 'off',
'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
'vue/component-name-in-template-casing': ['off', 'PascalCase'],
'vue/attribute-hyphenation': ['warn'],
'vue/no-unused-components': ['warn'],
'vue/html-self-closing': [
'error',
{
html: {
void: 'any',
normal: 'always',
component: 'always'
},
svg: 'always',
math: 'always'
}
],
'vue/max-attributes-per-line': 'off',
'vue/no-v-html': 'off',
'no-unused-vars': ['warn'],
eqeqeq: ['warn'],
'no-lonely-if': ['warn'],
'require-await': ['warn'],
'handle-callback-err': ['warn'],
'space-before-function-paren': 0
}
}
One other potential fix - but not for me
For anyone else with the same errors, there is a fix here, (that also worked for me): ESlint - Error: Must use import to load ES Module `
I cannot use this fix though, as my team suggested that adjusting babel settings can create errors elsewhere.
As that cannot be my solution, would anyone else know how to manage this error? Here is my nuxt.config file. If you need to see something else, I can update it here too.
nuxt.config
import { storyblokConfig, localeMessages } from './config'
export default {
// Target: https://go.nuxtjs.dev/config-target
target: 'server',
ssr: true,
dev: false,
// Global page headers: https://go.nuxtjs.dev/config-head
head: {
title: '',
htmlAttrs: {
lang: 'en'
},
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: '' }
],
link: [
{
rel: 'icon',
sizes: '192x192',
href: '/favicon/android-chrome-192x192.png'
},
{
rel: 'icon',
sizes: '512x512',
href: '/favicon/android-chrome-512x512.png'
},
{
rel: 'apple-touch-icon',
sizes: '180x180',
href: '/favicon/apple-touch-icon.png'
},
{ rel: 'icon', sizes: '16x16', href: '/favicon/favicon-16x16.png' },
{ rel: 'icon', sizes: '32x32', href: '/favicon/favicon-32x32.png' },
{ rel: 'icon', type: 'image/x-icon', href: '/favicon/favicon.ico' },
{ rel: 'manifest', href: '/favicon/site.webmanifest' }
]
},
// Global CSS: https://go.nuxtjs.dev/config-css
css: [
'~assets/styles/main.css',
'~assets/fonts/fabrikat/stylesheet.css',
'~assets/fonts/pangram/stylesheet.css'
],
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [
{ src: '~/plugins/logger.js' },
{ src: '~/plugins/nujek-ui.js' },
{ src: '~/plugins/validation.js' },
{ src: '~/plugins/utils.js' },
{ src: '~/plugins/vue-tailwind.js' },
{ src: '~/plugins/rich-text-renderer.js' },
{ src: '~/plugins/defaultButton.js' }
],
// Auto import components: https://go.nuxtjs.dev/config-components
components: [{ path: '~/components', pathPrefix: false, prefix: '' }],
// Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
buildModules: [
// https://go.nuxtjs.dev/eslint
'#nuxtjs/eslint-module',
// https://go.nuxtjs.dev/tailwindcss
'#nuxtjs/tailwindcss',
'#nuxtjs/composition-api/module',
'#nuxtjs/tailwindcss',
[
'#nujek/ui',
{
withConsole: true,
storeTemplates: {
nav: true
}
}
],
['#nujek/storyblok']
],
nujekStoryblok: {
storyblokConfig,
withConsole: false,
debug: true
},
// Modules: https://go.nuxtjs.dev/config-modules
modules: ['nuxt-i18n', '~/modules/nuxt-storyblok-queries/lib/module.js'],
storyblokQueries: storyblokConfig,
i18n: {
locales: [
{
code: 'en',
iso: 'en-US'
},
{
code: 'de',
iso: 'de-DE'
}
],
defaultLocale: 'de',
strategy: 'prefix_except_default',
detectBrowserLanguage: {
useCookie: true,
cookieKey: 'i18n_redirected',
redirectOn: 'root'
},
vueI18n: {
fallbackLocale: 'de',
silentTranslationWarn: true,
messages: localeMessages
},
vuex: {
syncLocale: true,
syncMessages: true
}
},
// publicRuntimeConfig: {
// accessToken: process.env.SB_CLIENT_ACCESS_TOKEN
// },
// Build Configuration: https://go.nuxtjs.dev/config-build
build: {
transpile: ['vee-validate', '#marvr/storyblok-rich-text-vue-renderer']
}
}
c:/users/user/AppData/Roaming/Code/User/settings.json
{
"workbench.colorTheme": "Default Dark+",
"terminal.integrated.defaultProfile.windows": "Git Bash",
"editor.wordWrap": "on",
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"eslint.validate": ["javascript"]
}
I met this error today on a fresh installation of nuxt.
It would npm run dev fine on the first time, but whenever I changed a file, the hot reloading would give an eslint error, as if trying to lint my eslint files.
I solved it by updating Nodejs and npm to their latest version and creating a new nuxt app.
It's probably not the answer you've been looking for, but maybe it will help others.

How to connect "html-minifier" to gulp?

I am using gulp and I get an error on startup...
How do I fix this?
The returned value is not a function.
I've been trying to fix this for hours now, but I don't understand what's wrong.
Maybe this is somehow possible using this plugin? vinyl-source-stream
const htmlMinify = require('html-minifier').minify
function html() {
const postcssPlugins = [
autoprefixer({
overrideBrowserslist: [
'>0.25%',
'not ie 11',
'not op_mini all'
]
}),
pxtorem({
rootValue: 16,
unitPrecision: 5,
propList: ['font', 'font-size', 'line-height', 'letter-spacing'],
replace: false,
mediaQuery: false,
minPixelValue: 0,
})
];
const postcssOptions = { from: undefined }
const filterType = /^text\/css$/
const plugins = [
posthtmlPostcss(postcssPlugins, postcssOptions, filterType)
];
const options = {
includeAutoGeneratedTags: true,
removeAttributeQuotes: true,
removeComments: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
sortClassName: true,
useShortDoctype: true
}
return src(config.app.html)
.pipe(include({ prefix: '##' }))
.pipe(posthtml(plugins))
.pipe(htmlMinify(options))
.pipe(dest(config.build.html))
}
exports.stream = series(clear, html, stream)
If using plugin "vinyl-source-stream".
The solution to this question would be the following code.
In this code, I used plugins that work with streams.
But this code only converts one file!
You can read more details about each plugin on npmjs.
html-minifier, vinyl-fs, vinyl-source-stream, map-stream
const { src, dest, series } = require('gulp');
const htmlMinify = require('html-minifier');
const vfs = require('vinyl-fs');
const source = require('vinyl-source-stream');
const map = require('map-stream');
const options = {
includeAutoGeneratedTags: true,
removeAttributeQuotes: true,
removeComments: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
sortClassName: true,
useShortDoctype: true,
collapseWhitespace: true
};
function sol() {
let minify = function(file, cb) {
cb(null, htmlMinify.minify(file.contents.toString(), options));
};
return vfs
.src(['app/index.html'])
.pipe(map(minify))
.pipe(source('index.html'))
.pipe(vfs.dest('build'));
}
exports.sol = series(sol);
This was the answer to this particular question.
There is a more elegant solution to this problem.
No third party plugins required. I described it in this post.

preserve json object used as dictionary with terser

I currently bundle my typescript code with rollup and want to use terser for minifying/uglifying. In my code I have a dictionary object and imported it into my typescript code.
const dict = { ironResource : "Iron" }
In my code I use it to translate identifiers to other languages or access configs by item identifiers (ironResource). Terser will mangle my keys and destroys the purpose of the object.
const B1 = { aB1 : "Iron" }
Terser settings:
terser({
parse: {
},
compress: {
},
mangle: {
properties: {
}
},
format: {
},
ecma: 5,
keep_classnames: false,
keep_fnames: false,
ie8: false,
module: false,
nameCache: null,
safari10: false,
toplevel: false,
})
How to stop terser from doing this?
I would expect that you need to set mangle like this:
mangle: {
properties: false
},
Or set the correct options in the properties option object to keep those in particular. For example quote the property names and set keep_quoted to true.

How to use markdown-it plugins options in nuxt.js

I'm using #nuxtjs/markdownit to parse markdown files, I want to enable creating permanent links feature in 'markdown-it-anchor' plugin, I used following code in nuxt.config.js but not working:
modules: [
// Doc: https://axios.nuxtjs.org/usage
'#nuxtjs/axios',
'#nuxtjs/markdownit'
],
markdownit: {
preset: 'default',
linkify: true,
breaks: true,
typographer: true,
html: false,
use: [
'markdown-it-anchor',
'markdown-it-attrs',
'markdown-it-div',
'markdown-it-toc-done-right',
'markdown-it-emoji'
]
},
'markdown-it-anchor': {
level: 1,
// slugify: string => string,
permalink: true,
// renderPermalink: (slug, opts, state, permalink) => {},
permalinkClass: 'header-anchor',
permalinkSymbol: '¶',
permalinkBefore: true
},
Self answering: I found the syntax in this post
markdownit: {
preset: 'default',
linkify: true,
breaks: true,
typographer: true,
html: false,
use: [
[
'markdown-it-anchor',
{
level: 1,
// slugify: string => string,
permalink: true,
// renderPermalink: (slug, opts, state, permalink) => {},
permalinkClass: 'header-anchor',
permalinkSymbol: '¶',
permalinkBefore: true
}
],
'markdown-it-attrs',
'markdown-it-div',
'markdown-it-toc-done-right',
'markdown-it-emoji'
]
},

i18next::backendConnector: loaded namespace translation for language en

this my code
const fallbackLng = ["en"];
const availableLanguages = ["en", "ru"];
i18n
.use(Backend)
.use(LanguageDetector)
.use(initReactI18next)
.init({
fallbackLng,
debug: true,
whitelist: availableLanguages,
interpolation: {
escapeValue: false
}
});
I see strange lines in the console
i18next::backendConnector: loaded namespace translation for language en {Form: {…}, SignUp: {…}, SignIn: {…}}
i18next::backendConnector: loaded namespace translation for language ru {Form: {…}, SignUp: {…}, SignIn: {…}}
i18next: languageChanged ru
i18next: initialized {debug: true, initImmediate: true, ns: Array(1), defaultNS: Array(1), fallbackLng: Array(1), …}
all code can be seen here codesandbox
Set debug to false in that object
{
fallbackLng,
debug: false,
whitelist: availableLanguages,
interpolation: {
escapeValue: false
}
}

Categories