@erect/config

0.0.16 • Public • Published

Erect Config Utility

A configuration utility valid for both client and server

Key aspects

  • Exports config safely to browser
  • Typed config structure
  • Import config related to project

How to use it

  1. Create a config directory in your project's root path
  2. Create your config schema in config/schema.ts
import {
  ConfigSource as BaseConfigSource,
  ConfigCallable,
} from '@erect/config';

export { BaseConfigSource };

interface MyConfigSource {
  server: {
    address: string;
    port: number;
  },
  htmlPage: {
    welcomeMessage: string;
    secret: string;
  },
}

export interface ConfigSource extends BaseConfigSource, MyConfigSource {}
export interface ConfigSourceValues extends Partial<BaseConfigSource>, MyConfigSource {}
export type Config = ConfigCallable & ConfigSource;
  1. Create config/clientConfigFilter.ts and define which config should be safely exported to client
export default {
  htmlPage: {
    welcomeMessage: true,
  },
}
  1. Create config/values.ts and export your config values as default wrapped in an arrow function
import { ConfigSource } from './schema';
import clientConfigFilter from './clientConfigFilter';
import * as EnvVars from '@erect/config/EnvVars';

export default (): ConfigSource => ({
  clientConfigFilter,
  server: {
    address: envVars.string('LISTEN_ADDRESS', '0.0.0.0'),
    port: envVars.number('LISTEN_PORT', 1337),
  },
  htmlPage: {
    welcomeMessage: 'Hello World',
    secret: 'My Secret',
  },
});
  1. Create your config/index.ts to be imported in both client and server
import { config as baseConfig } from '@erect/config';
import { Config } from './schema';
export * from '@erect/config';
export { Config, ConfigSource } from './schema';
export const config = <Config>baseConfig;
export default config;
  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 '@erect/config/server';
console.log(renderClientConfig('your nonce here'));

outputs

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

Package Sidebar

Install

npm i @erect/config

Weekly Downloads

19

Version

0.0.16

License

MIT

Unpacked Size

40.8 kB

Total Files

32

Last publish

Collaborators

  • ezsper