@erect/config
v0.0.16
Published
A configuration utility valid for both client and server
Downloads
16
Maintainers
Readme
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
- Create a
config
directory in your project's root path - 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;
- Create
config/clientConfigFilter.ts
and define which config should be safely exported to client
export default {
htmlPage: {
welcomeMessage: true,
},
}
- 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',
},
});
- 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;
- 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>