Load any json file at build time using babel-plugin-macros.
json.macro
is designed to be used with babel-plugin-macros to inline all your json file imports.
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',
]
}
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');
↓ ↓ ↓ ↓ ↓ ↓
const myJson = { custom: 1 };
Like magic :-)
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. |
Get the semver compatible version from the package.json file.
export function getVersion(verbose?: false): string;
export function getVersion(verbose: true): SemanticVersion;
Parameter | Type | Description |
---|---|---|
verbose | boolean |
When true will return an object representing the semantic version |
This will throw a build error if the semver version in your package.json is not valid.
import { getVersion } from 'json.macro';
const versionString = getVersion();
const versionStringAlt = getVersion(false);
const versionObject = getVersion(true);
↓ ↓ ↓ ↓ ↓ ↓
const versionString = '1.19.2';
const versionStringAlt = '1.19.2';
const versionObject = { major: 1, minor: 19, patch: 2, version: '1.19.2' };
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;
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 |
For the following json file: ./my-json.json
{
"custom": 1
}
This is how to load it at build time.
import { loadJson } from 'json.macro';
const myJson = loadJson('my-json.json');
↓ ↓ ↓ ↓ ↓ ↓
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;
Load all the json files matching the provided patterns.
export function loadJsonFiles<Type>(
pattern: string,
...patterns: string[]
): Type[];
Parameter | Type | Description |
---|---|---|
pattern | string |
This function requires at least one json file pattern |
...patterns | string[] |
Multiple patterns can be also be added. |
If no files match then an empty array is returned.
import { loadJsonFiles } from 'json.macro';
const jsonArray = loadJsonFiles('*.json');
↓ ↓ ↓ ↓ ↓ ↓
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');
Load the nearest parent package.json
file.
export function loadPackageJson(): PackageJson;
export function loadPackageJson<Key extends string>(key: Key): PackageJson[Key];
Parameter | Type | Description |
---|---|---|
key | keyof PackageJson |
The property you want to load from the package.json file |
You can also provide a key property which will load the property corresponding to the key from the nearest package.json
.
import { loadPackageJson } from 'json.macro';
const packageJson = loadPackageJson();
const name = loadPackageJson('name');
↓ ↓ ↓ ↓ ↓ ↓
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
library.
Load the nearest parent tsconfig.json
file.
export function loadTsConfigJson(): TsConfigJson;
You can customise the name of the file searched for.
import { loadTsConfigJson } from 'json.macro';
const tsconfig = loadTsConfigJson();
const customTsConfig = loadTsConfigJson('tsconfig.custom.json');
↓ ↓ ↓ ↓ ↓ ↓
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.
Write a JSON object to a relative file path.
export function writeJson<Type>(json: Type, filePath: string): Type;
Parameter | Type | Description |
---|---|---|
json | any |
The json object to be written |
filePath | string |
Where the json object will be written to. |
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.
import { writeJson } from 'json.macro';
type Config = {config: boolean, type: 'string' | 'array' };
const json = writeJson<Config>({config: true, type: 'array'}, './config.json);
↓ ↓ ↓ ↓ ↓ ↓
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 ❌
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;
Dive into the codebase with Gitpod.
This project uses SemVer for versioning. For the versions available, see the tags on this repository.
This project is licensed under the MIT License - see the LICENSE file for details
Ifiok Jr. 💻 |