1.3.0 • Published 4 years ago

json.macro v1.3.0

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

json.macro

GitHub Actions Build Status Version Weekly Downloads Typed Codebase MIT License semantic-release

Load any json file at build time using babel-plugin-macros.

Table of Contents

Usage

json.macro is designed to be used with babel-plugin-macros to inline all your json file imports.

Setup

First, install the plugin and it's peer dependency (babel-plugin-macros). Since the macro is compiled away during the build, it should be installed as a development dependency.

npm install --save-dev json.macro babel-plugin-macros

or

yarn add -D json.macro babel-plugin-macros

Once installed make sure to add the 'babel-plugin-macros' to your babel.config.js (or .babelrc) file.

.babelrc

{
  "plugins": [
    "other-plugins",
+   "macros",
  ]
}

babel.config.js

module.exports = {
  // rest of config...,
  plugins: [
    ...otherPlugins,
+   'macros',
  ]
}

Code Example

For the following json file: ./my-json.json this code will load a json file from the provided path. The path can be relative to the file it's being used from or an absolute path. If the file can't be resolved the build will fail.

/path/to/my-json.json

{
  "custom": 1
}

This will load it

/path/to/my-js.js

import { loadJson } from 'json.macro';

const myJson = loadJson('./my-json.json');

Compiles to ↓ ↓ ↓ ↓ ↓ ↓

const myJson = { custom: 1 };

Like magic :-)

API

FunctionDescription
getVersion(verbose)Get the semver compatible version from the package.json file.
loadJson(filePath, path)This loads a json file from the provided path. The path can be relative to the file it's being used from, an absolute path, or a path to your node_modules folder.If the file can't be resolved the build will fail.
loadJsonFiles(pattern, ...patterns)Load all the json files matching the provided glob patterns.
loadPackageJson()Load the nearest parent package.json file.
loadTsConfigJson()Load the nearest parent tsconfig.json file.
writeJson(json, filePath)Write a json object to a relative file path.

getVersion()

Get the semver compatible version from the package.json file.

export function getVersion(verbose?: false): string;
export function getVersion(verbose: true): SemanticVersion;

Parameters

ParameterTypeDescription
verbosebooleanWhen true will return an object representing the semantic version

Description

This will throw a build error if the semver version in your package.json is not valid.

Example

import { getVersion } from 'json.macro';

const versionString = getVersion();
const versionStringAlt = getVersion(false);
const versionObject = getVersion(true);

Compiles to ↓ ↓ ↓ ↓ ↓ ↓

const versionString = '1.19.2';
const versionStringAlt = '1.19.2';
const versionObject = { major: 1, minor: 19, patch: 2, version: '1.19.2' };

loadJson()

This loads a json file from the provided path. The path can be relative to the file it's being used from, an absolute path, or a path to your node_modules folder.

If the file can't be resolved the build will fail.

export function loadJson<Type>(filePath: string, path?: string): Type;

Parameters

ParameterTypeDescription
filePathstringthe relative file path to reference
pathstringthe object path for the part of the object you want to load

Description

For the following json file: ./my-json.json

{
  "custom": 1
}

This is how to load it at build time.

Examples

import { loadJson } from 'json.macro';

const myJson = loadJson('my-json.json');

Compiles to ↓ ↓ ↓ ↓ ↓ ↓

const myJson = { custom: 1 };

Magic :-)

To load from node_modules you can do something like the following.

import { loadJson } from 'json.macro';

const jsonFromNode = loadJson('json.macro/package.json');

The above will be replaced with the full package.json file from the json.macro node_modules package.

If you are using typescript you can specify the expected return type by annotating the variable created.

import { loadJson } from 'json.macro';

const myJson: { custom: number } = loadJson('my-json.json');

If a second parameter is passed, this can also load a specific key path from a json file.

./my-json.json

{
  "a": {
    "b": { "c": { "d": 1 } },
    "arr": [1, 2, 3, 4, { "end": true }]
  }
}
import { loadJsonPath } from 'json.macro';

const value = loadJsonPath('my-json.json', 'a.b.c.d');
const value2 = loadJsonPath('my-json.json', 'a.arr.4.end');

Compiles to ↓ ↓ ↓ ↓ ↓ ↓

const value = 1;
const value2 = true;

loadJsonFiles()

Load all the json files matching the provided patterns.

export function loadJsonFiles<Type>(
  pattern: string,
  ...patterns: string[]
): Type[];

Parameters

ParameterTypeDescription
patternstringThis function requires at least one json file pattern
...patternsstring[]Multiple patterns can be added

Description

If no files match then an empty array is returned.

Examples

import { loadJsonFiles } from 'json.macro';

const jsonArray = loadJsonFiles('*.json');

Compiles to ↓ ↓ ↓ ↓ ↓ ↓

const jsonArray = [{ custom: 1 }, { another: 2 }];

If you are using typescript you can specify the expected return type by annotating the variable created.

import { loadJsonFiles } from 'json.macro';

const jsonArray: Array<{ custom: string }> = loadJsonFiles('*.json');

loadPackageJson()

Load the nearest parent package.json file.

export function loadPackageJson(): PackageJson;
export function loadPackageJson<Key extends string>(key: Key): PackageJson[Key];

Parameters

ParameterTypeDescription
keykeyof PackageJsonThe property you want to load from the package.json file

Description

You can also provide a key property which will load the property corresponding to the key from the nearest package.json.

Examples

import { loadPackageJson } from 'json.macro';

const packageJson = loadPackageJson();
const name = loadPackageJson('name');

Compiles to ↓ ↓ ↓ ↓ ↓ ↓

const packageJson = { name: 'my-package', version: '1.0.0', private: true };
const name = '1.0.0';

For typescript users, the types are automatically inferred using the PackageJson type from the [type-fest](https://github.com/sindresorhus/type-fest) library.

loadTsConfigJson()

Load the nearest parent tsconfig.json file.

export function loadTsConfigJson(): TsConfigJson;

Remarks

You can customise the name of the file searched for.

Example

import { loadTsConfigJson } from 'json.macro';

const tsconfig = loadTsConfigJson();
const customTsConfig = loadTsConfigJson('tsconfig.custom.json');

Compiles to ↓ ↓ ↓ ↓ ↓ ↓

const tsconfig = { compilerOptions: {} };
const customTsConfig = { compilerOptions: { paths: [] } };

For typescript users, the types are automatically inferred using the TsConfigJson type from the [type-fest](https://github.com/sindresorhus/type-fest) library.

writeJson()

Write a JSON object to a relative file path.

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

Parameters

ParameterTypeDescription
jsonanyThe json object to be written
filePathstringWhere 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 ❌

json.macro/types

You might find yourself wanting to use the PackageJson or TsConfigJson types in your own code. For this reason this file re-exports them from type-fest to save you the hassle of adding another direct dependency.

import { PackageJson, TsConfigJson } from 'json.macro/types';

let pkg: PackageJson;
let tsconfig: TsConfigJson;

There is also a SemanticVersion interface which exported by the same file. This is the return type for the getVersion(true) function call.

import { SemanticVersion } from 'json.macro/types';

let version: SemanticVersion;

Contributing

Dive into the codebase with Gitpod.

Open in Gitpod

Versioning

This project uses SemVer for versioning. For the versions available, see the tags on this repository.

License

This project is licensed under the MIT License - see the LICENSE file for details

Contributors