Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add writeJson method #2

Merged
merged 2 commits into from
May 9, 2020
Merged

feat: add writeJson method #2

merged 2 commits into from
May 9, 2020

Conversation

ifiokjr
Copy link
Owner

@ifiokjr ifiokjr commented May 9, 2020

Description

writeJson()

Write a JSON object to a relative file path.

export function writeJson<Type>(json: Type, filePath: string): Type;

Parameters

Parameter Type Description
json any The json object to be written
filePath string Where the json object will be written to.

Returns:

Type

Remarks

Sometimes it's easier to create an object that needs to follow certain type rules in typescript and then export it to a JSON object. How to do this though?

This method wraps the JSON object you create (statically and not dynamically) and will output to the provided filePath at build time.

Examples

import { writeJson } from 'json.macro';

type Config = {config: boolean, type: 'string' | 'array' };
const json = writeJson<Config>({config: true, type: 'array'}, './config.json);

Compiles to ↓ ↓ ↓ ↓ ↓ ↓

const json = { config: true, type: 'array' };

And ./config.json is written as.

{
  "config": true,
  "type": "array"
}

One thing to be aware of is that this method only supports inline or statically inferable values. You can't use any dynamic values, like return values from a function call.

import { writeJson } from 'json.macro';

const json = { custom: 'custom' };
const createJson = () => json;

writeJson({ a: true }, './file.json'); // Static ✅
writeJson(custom, './file.json'); // Static ✅

writeJson(createJson(), './file.json'); // Dynamic ❌

Checklist

  • My code follows the code style of this project and yarn lint --fix runs successfully.
  • I have updated the documentation where necessary.
  • New code is unit tested and all current tests pass when running yarn test .

@ifiokjr ifiokjr merged commit 6918107 into master May 9, 2020
@ifiokjr ifiokjr deleted the write-json branch May 9, 2020 12:45
github-actions bot pushed a commit that referenced this pull request May 9, 2020
## [1.3.0](v1.2.4...v1.3.0) (2020-05-09)

### Features

* add `writeJson` method ([#2](#2)) ([6918107](6918107))
@github-actions
Copy link

github-actions bot commented May 9, 2020

🎉 This PR is included in version 1.3.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant