@spine/config

A configuration utility valid for both client and server

Stats

StarsIssuesVersionUpdatedCreatedSize
@spine/config
0.0.403 years ago3 years agoMinified + gzip package size for @spine/config in KB

Readme

Spine Config Utility

A configuration utility valid for both client and server

Key aspects

  • Exports config safely on browser
  • Typed config structure
  • Namespaces

How to use it

  1. Create a config directory in your project's root path

  2. Create config/clientConfigFilter.ts and define which config should be safely exported to client

import { ConfigSource } from '.';

export const clientConfigFilter: ConfigSource['clientConfigFilter'] = {
  htmlPage: {
    welcomeMessage: true,
  },
}
  1. Create your config/index.ts to be imported in both client and server
import {
  createConfig,
  ClientConfigFilter,
} from '@spine/config';

export interface MyProjectConfigSource {
  clientConfigFilter: ClientConfigFilter<this>;
  port: number;
  host: string;
  htmlPage: {
    welcomeMessage: string;
  };
}

export interface ConfigSource extends MyProjectConfigSource {}
export const config = createConfig<ConfigSource>('MyProject', '__CONFIG__');
export default config;

const isBrowser = typeof window !== 'undefined';

if (isBrowser) {
  config.hydrate();
} else {
  require('./load');
}
  1. Create config/load.ts and load your config
import * as envVars from '@spine/config/envVars';
import { config } from '.';
import { clientConfigFilter } from './clientConfigFilter';

config.load({
  clientConfigFilter,
  port: envVars.number('PORT', 1337),
  host: envVars.number('HOST', '0.0.0.0'),
  htmlPage: {
    welcomeMessage: 'Welcome',
  },
});
  1. Start using your config inside your project
import config from '../config';
console.log(config.htmlPage.welcomeMessage);
console.log(config('htmlPage.welcomeMessage'));

Export config from your server to your client

import { renderClientConfig } from '@spine/config/server';
import { config } from './config';
console.log(renderClientConfig(config, config.clientConfigFilter, 'your nonce here'));

outputs

<script nonce="your nonce here">
window.__CONFIG__={
    htmlPage: {
      welcomeMessage: "Hello World"
    },
}
</script>

If you find any bugs or have a feature request, please open an issue on github!

The npm package download data comes from npm's download counts api and package details come from npms.io.