Namespaces
You may have heard of namespaces in other programming languages, such as Java or C++. In JavaScript, namespaces are simply named objects in the global scope. They serve as a region in which variables, functions, interfaces, or classes are organized and grouped together within a local scope to avoid naming conflicts between components in the global scope.
While modules are also used for code organization, namespaces are more straightforward to implement for simple use cases. However, modules offer additional benefits such as code isolation, bundling support, re-exporting components, and renaming components that namespaces do not provide.
In my own projects, I find namespaces useful for grouping styles when using styled-components
, for instance:
import styled from 'styled-components'
export namespace CSS {
export const InputWrapper = styled.div`
padding: 10px;
margin: 0;
background: white;
width: 250px;
`
export const InputBase = styled.input`
width: 100%;
background: transparent;
border: none;
font-size: 14px;
`
}
Then when I need to use it, I consume it like this:
import React, { ComponentPropsWithoutRef, FC } from 'react'
import { CSS } from './Input.styled'
export interface Props extends ComponentPropsWithoutRef<'input'> {
error?: boolean
}
const Input: FC<Props> = ({
type = 'text',
error = false,
value = '',
disabled = false,
...restProps
}) => (
<CSS.InputWrapper style={error ? { border: '1px solid red' } : {}}>
<CSS.InputBase type={type} value={value} disabled={disabled} {...restProps} />
</CSS.InputWrapper>
)
This is very useful because I don’t need to worry about exporting multiple styled components. I just export the CSS namespace and I can use all the styled components defined inside that namespace.