npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

json.macro

v1.3.0

Published

Directly load json files into your code via babel macros.

Downloads

3,566

Readme

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

| Function | Description | | ------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 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

| Parameter | Type | Description | | --------- | --------- | ----------------------------------------------------------------- | | verbose | boolean | When 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

| Parameter | Type | Description | | --------- | -------- | ----------------------------------------------------------- | | filePath | string | the relative file path to reference | | path | string | the 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

| Parameter | Type | Description | | ------------- | ---------- | ----------------------------------------------------- | | pattern | string | This function requires at least one json file pattern | | ...patterns | string[] | 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

| Parameter | Type | Description | | --------- | ------------------- | ---------------------------------------------------------- | | key | keyof PackageJson | The 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

| 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 ❌

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