I have a javascript file where I simply define the css classes so I can use them through out my code and can maintain them in one place, like this:
//css.js
const pre = 'grc-';
const backdropcss = {
backdrop: `${pre}backdrop`,
};
const buttoncss = {
btn: `${pre}btn`,
btnSm: `${pre}btn--sm`,
btnSecondary: `${pre}btn--secondary`,
btnTertiary: `${pre}btn--tertiary`,
btnLink: `${pre}btn--link`,
btnFull: `${pre}btn--full`,
btnHalf: `${pre}btn--half`,
btnThird: `${pre}btn--third`,
};
//etc.
I am using it in two ways. For my component library I like to isolate the css names for the components like this:
export {
buttoncss,
alertcss,
checkboxcss,
formcss,
radioboxcss,
drawercss,
backdropcss,
rangecss,
};
So I can import only what I need.
But I also want a default export where all the definitions are combined.
(Note: so I don't want to use them as cssjs.buttoncss
but rather as cssjs
which has all the sub objects spread into)
To create the object I spread all the sub objects and then I export it as default, like this:
const cssjs = {
...buttoncss,
...alertcss,
...checkboxcss,
...formcss,
...radioboxcss,
...drawercss,
...backdropcss,
...rangecss,
};
export default cssjs;
Now, every time I create a new components it feels redundant to add it twice in those objects. So I wanted to create an all
object:
const all = {
buttoncss,
alertcss,
checkboxcss,
formcss,
radioboxcss,
drawercss,
backdropcss,
rangecss,
};
And spread them into the (named) export(s):
export { ...all}
Then I'll write some code to loop through the all
object and spread every sub object into one big object (to create the cssjs
object from before).
But before I was able to write that last code I noticed that the export { ...all}
syntax was not supported. Is there any way to accomplish what I want, or do I have to write everything twice like I do now?
EDIT:
Re-using variables if you set them as exports when declaring threw me off guard. This my code now:
//more definitions
export const formcss = {
formGroup: `${pre}form--group`,
};
export const radioboxcss = {
radio: `${pre}radio`,
radioStacked: `${pre}radio--stacked`,
};
export default {
...buttoncss,
...alertcss,
...checkboxcss,
...formcss,
...radioboxcss,
...drawercss,
...backdropcss,
...rangecss,
};
This solved my particular question, but still makes me wonder why it's not possible to spread an object into an export declaration so you can export everything in the object as named within the object. So for other people who might come here through the title:
Why can I do this
const one = 1
const two = 2
export { one, two, }
But not this
const one = 1
const two = 2
const numbers = { one, two, }
export { ...numbers, }