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

@postinumero/unplugin-config

v0.1.0

Published

A plugin for managing build-time and runtime configuration across multiple build tools.

Downloads

111

Readme

@postinumero/unplugin-config

A plugin for managing build-time and runtime configuration across multiple build tools, supporting key unflattening, JSON parsing, prefix removal, and merging of default, build-time, and runtime configuration sources.

Setup with Build Tools

Add @postinumero/unplugin-config to your build tool’s configuration.

// vite.config.ts
import Config from "@postinumero/unplugin-config/vite";

export default defineConfig({
  plugins: [
    Config({
      /* options */
    }),
  ],
});

Example

// rollup.config.js
import Config from "@postinumero/unplugin-config/rollup";

export default {
  plugins: [
    Config({
      /* options */
    }),
  ],
};

// webpack.config.js
module.exports = {
  /* ... */
  plugins: [
    require("@postinumero/unplugin-config/webpack")({
      /* options */
    }),
  ],
};

// nuxt.config.js
export default defineNuxtConfig({
  modules: [
    [
      "@postinumero/unplugin-config/nuxt",
      {
        /* options */
      },
    ],
  ],
});

Supports both Nuxt 2 and Nuxt Vite.

// vue.config.js
module.exports = {
  configureWebpack: {
    plugins: [
      require("@postinumero/unplugin-config/webpack")({
        /* options */
      }),
    ],
  },
};

// esbuild.config.js
import { build } from "esbuild";
import Config from "@postinumero/unplugin-config/esbuild";

build({
  plugins: [
    Config({
      /* options */
    }),
  ],
});

Usage

Step 1: Define Default Configuration

Add a config.json file with default configuration values. This is also the base for TypeScript type declarations.

Example: config.json

{
  "string": "hello",
  "boolean": false,
  "number": 123,
  "some": {
    "nested": {
      "value": "default value"
    },
    "other": "other default value"
  },
  "more": [123, "foo"]
}

Step 2: Set Build-Time Configuration Overrides

Override specific config values at build time by defining environment variables.

Example: .env

VITE_string=build-time value
VITE_boolean=true
VITE_number=456
VITE_some.nested.value=some nested environment value
VITE_more=[456,"bar"]

Step 3: Add Runtime Configuration Overrides

Add runtime config overrides by creating a config.json file in the project’s public directory. These values will be merged into the final configuration.

Example: public/config.json

{
  "string": "runtime value",
  "more.2": 789
}

Step 4: Import and Use Config

You can import configuration using different formats based on your project’s needs. Additionally, you can add type declarations.

Available Import Formats

| Format | Import Path | Description | | ---------------------------- | ----------------- | ----------------------------------------------------------------------------------------------- | | Awaited | ~config | Direct access to config as an object. Requires support for top-level await. | | Promise | ~config/promise | Config wrapped in a promise. | | Ref | ~config/ref | Reference-style access with .ready promise and .current as null \| Config. | | Proxy | ~config/proxy | Experimental proxy-based config with ready promise to ensure data availability before access. | | Raw | ~config/raw | Access raw, unprocessed config sources as an array. |

Example Usage

// Import configuration in the format that suits your use case
import config from "~config"; // Requires support for top-level await

console.log(config.some.nested.value); // Access config properties directly

The following example configuration output demonstrates how values are merged across default, build-time, and runtime sources:

{
  "string": "runtime value",
  "boolean": true,
  "number": 456,
  "some": {
    "nested": {
      "value": "some nested environment value"
    },
    "other": "other default value"
  },
  "more": [456, "bar", 789]
}

Type Declarations for TypeScript

To use config imports with TypeScript, add one or more of the following declarations based on the desired formats:

// config.d.ts
type Config = typeof import("./config.json");

declare module "~config" {
  const config: Config;
  export default config;
}

declare module "~config/promise" {
  const config: Promise<Config>;
  export default config;
}

declare module "~config/ref" {
  const config: {
    ready: Promise<void>;
    current: Config | null;
  };
  export default config;
}

declare module "~config/proxy" {
  const config: Config;
  export default config;
  export const ready: Promise<void>;
}

declare module "~config/raw" {
  const config: (Config | Promise<Config>)[];
  export default config;
}

Options

Option Types and Defaults

Configure sources and modifiers with defaults for a seamless setup.

| Option | Type | Default | Description | | ---------------- | ------------------ | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | | importPath | string | "~config" | Import path alias for the config. | | file | string \| false | "config.json" | File source for config. | | global | string \| false | "process.env" ("import.meta.env" in Vite) | Environment variable source. | | fetch | string \| false | "config.json" | URL or path to fetch config from. In the case of a relative path, it will be prefixed with import.meta.env.BASE_URL (if available). | | stripPrefix | string \| false | "VITE_" (in Vite) "FARM_" (in Farm) | Prefix to remove from config variable names. | | parseJsonValue | boolean \| false | undefined (enabled by default) | Whether to parse JSON values from config variable values. | | unflat | boolean \| false | undefined (enabled by default) | Whether to unflat config variable names. | | sources | SourceOption[] | Defined below | Config sources that are merged from left to right. | | modifiers | ModifierOption[] | Defined below | Config transformations that are run in given order before configs are merged. |

Default Sources

[
  ["file", options.file],
  ["global", options.global],
  ["fetch", options.fetch],
];

Default Modifiers

[
  ["strip-prefix", options.stripPrefix],
  ["parse-json-values", options.parseJsonValue],
  ["unflat", options.unflat],
];

Options as Search Parameters

You can also set options directly in the import path by adding them as search parameters. If any search parameter is specified in the import path, all default options and plugin configuration options are bypassed, and only the search parameters are used.

Example:

import config from "~config?file=config-a.json&file=config-b.json&global=import.meta.env&strip-prefix=VITE_";

console.log(config);

Formats

Configuration can be accessed in different formats depending on your project’s needs.

Awaited

This format requires support for top-level await.

import config from "~config";

console.log(config.some.nested.value);

Promise

This format returns a promise that resolves to the configuration object.

import configPromise from "~config/promise";

async function func() {
  const config = await configPromise;

  console.log(config.some.nested.value);
}

Ref

This format provides a reference object that can be accessed synchronously. Initially, current is null until the config is ready.

import configRef from "~config/ref";

function func() {
  const config = configRef.current; // null | Config

  console.log(config?.some.nested.value);
}

async function otherFunc() {
  await configRef.ready;

  const config = configRef.current!; // Config is ready

  console.log(config.some.nested.value);
}

Proxy (Experimental)

This experimental format uses a proxy to access the configuration. It throws an error if the configuration is accessed before it is ready.

import config, { ready } from "~config/proxy";

console.log(config.some.nested.value); // May throw an error if accessed too early

async function func() {
  await ready;

  console.log(config.some.nested.value); // Safe to access after `ready` resolves
}

Raw

Access raw configuration data as an array without processing.

import raw from "~config/raw";

async function func() {
  const configs = await Promise.all(raw);

  console.log(configs); // [defaults, env, runtime]
}