Currently, there is no known solution for this issue other than making changes to the webpack configuration itself. The problem arose because Create React App (CRA) likely uses mode
: local
, whereas Next.js uses pure
.
Though I have not personally tried overriding the css-loader
webpack config, I am suggesting a workaround approach. If you are working with SCSS, you can encapsulate your pseudo-global styles like this:
.root :global {
.foo {
color: red;
}
}
To implement this, wrap your component/page in a div
element and assign the class as styles.root
to that element. Subsequently, you can directly apply className="foo"
to all child elements.
import styles from "../styles/index.module.scss";
const IndexPage = () => (
<div className={styles.root}>
<div className="foo">This text will appear in red!</div>
</div>
);
export default IndexPage;
Please be aware of specificity issues that may arise after following this method. Additionally, direct application of animations may require separating the keyframes
and making them globally accessible.
Check out the Demo Sandbox
[1]: It's important to note that this method does not make the styles entirely global since they remain scoped. The class foo
will only function if some parent element has styles.root
as its class attribute. This approach is ideal if you didn't initially intend to utilize your :global(.selector)
in other components, and were merely using it to dynamically manage class names via JavaScript without the use of a styles object.
If true global styling is required, consider adding styles.root
to document.documentElement
within a useEffect
hook as shown below:
import { useEffect } from "react";
import styles from "../styles/index.module.scss";
const IndexPage = () => {
useEffect(() => {
document.documentElement.classList.add(styles.root);
return () => {
document.documentElement.classList.remove(styles.root);
};
}, []);
return (
<div className="foo">
This text will display in red, even if placed within another component on the same page. For consistent application across multiple pages, inject it in _app or _document.
</div>
);
};
export default IndexPage;
View the Demo Sandbox
PS: Adding classes to html
within _app
or _document
is not identical to utilizing a global stylesheet. In the case of a multi-page application, automatic CSS code-splitting by Next.js may result in only the necessary CSS being requested per page due to each component having distinct CSS. However, if all pages share the same CSS, sticking to the conventional method of importing styles in _app
would suffice.