@spine/config
v0.0.40
Published
A configuration utility valid for both client and server
Downloads
22
Maintainers
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
Create a
config
directory in your project's root pathCreate
config/clientConfigFilter.ts
and define which config should be safely exported to client
import { ConfigSource } from '.';
export const clientConfigFilter: ConfigSource['clientConfigFilter'] = {
htmlPage: {
welcomeMessage: true,
},
}
- 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');
}
- 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',
},
});
- 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>