0.0.1 • Published 4 years ago

webpack-i18n-js-to-json v0.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
4 years ago

Webpack i18n js to json serves to remove the complexity of maintaining the JSON translation files by creating the files using JS/TS while giving the developer the ability to use the same key for the file and for the t(variable).

Why?

While developing the translation JSON files to use with i18next-http-backend I always had problems in making sure the keys in the translation file and the keys in the t("key") are the same and the keys in the file are actually being used, especially in projects with multiple developers. So this packages serves as a starting point to try to fix this problem.

How to install

npm install webpack-i18n-js-to-json --save-dev

Options

const { WebpackI18nJsToJson } = require('webpack-i18n-js-to-json');

module.exports = {
  //...
  plugins: [
    new WebpackI18nJsToJson({
      // Path where the translations files are located:
      // "language abbreviation/locale codes".js/ts ex:"en.ts"
      srcPath: "./src/assets/locales",
      // Folder where the json files will be created (build/locales/*.json)
      basePath: "/locales",
    }),
  ],
  //...
};

Note: The basePath needs to match the loadPath from the options in i18next-http-backend for it to work.

...
{
	loadPath: '/locales/{{lng}}.json'
}
...
NameDefaultRequiredDescription
srcPathtruePath where it will search for the translations files
basePath'/'falseFolder/Place where it will generate the json files

Example

src/assets/locales/variables.ts

// Even though this file is on the same folder as the other locales,
// the system will only create files whose name is accepted in
// Intl.NumberFormat.supportedLocalesOf(locale)
// (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/supportedLocalesOf)
export const learn = "learn_key";
export const welcome = "welcome";

src/assets/locales/pt.ts

import { learn, welcome } from './variables';

const translation = {
	[learn]: 'Aprender',
	[welcome]: 'Hi'
}
export default translation;

// Result /locales/pt.json

{"learn_key":"Aprender", "welcome":"Hi"}

src/assets/locales/en.ts

import { learn, welcome } from './variables';

const translation = {
	[learn]: 'Learn',
	[welcome]: 'Hello'
}

export default translation;

// Result /locales/en.json

{"learn_key":"Learn", "welcome":"Hello"}

Missing keys

During the production build it will check if all the translations files have the same keys. If there are any missing keys it will stop the building process and show the missing keys.