1.0.0 • Published 6 years ago

webpack-typescript-json-type v1.0.0

Weekly downloads
2
License
MIT
Repository
github
Last release
6 years ago

webpack-typescript-json-type NPM version Build Status Dependency Status

Generates a type with all json paths for the configured files

Installation

$ npm install --save-dev webpack-typescript-json-type

Usage

const path = require('path');
const TranslationKeyTypeGenerator = require('webpack-typescript-json-type');

then use it in the plugins section of your config:

{
  plugins: [
    new TranslationKeyTypeGenerator({ 
      files: [
        { path: path.resolve(__dirname, './path/to/your/json.json'), class: 'SomeTypeName' },
        { path: path.resolve(__dirname, './path/to/your/different.json.json'), class: 'ADifferentTypeName' },
      ], 
      output: path.resolve(__dirname, 'typings_custom'),
      typefile: 'optional.d.ts' // Defaults to jsontypes.d.ts
    })
}

This will produce to ambient types SomeTypeName and ADifferentTypeName in the specified file. Then you just need to include the type definition file with a reference path and you're good to go /// <reference path="path/to/jsontypes.d.ts"/> or include it differently.

Example

Consider the following file structure (maybe used as a translation file in a webproject).

{
   "MAIN": {
      "TITLE": "Main",
      "WELCOME": "Welcome Message"
    },
    "ABOUT": {
      "TITLE": "About"
    }
}

In most i18n implementations these translations can be used in the form MAIN.TITLE or ABOUT.TITLE. Using webpack-typescript-json-type with the above file content (giving it the name TranslationKey) will produce the following type:

declare type TranslationKey = 'MAIN.TITLE' | 'MAIN.WELCOME' | 'ABOUT.TITLE';

This type then allows your IDE to autocomplete translation keys if typed correctly.

License

MIT © Gabriel Nadler