Load and swich between css themes files easily.
npm i lazy-theme-changer
or
yarn add lazy-theme-changer
Fisrt of all you have to identify your theme file by one of this way:
You are using webpack and style-loader, use webpack's inline loader systax to add an atribute data-theme
in style tag when the file is loaded.
By doing something like:
const theme = () =>
import(
/* webpackChunkName: "theme-dark" */
/* webpackMode: "lazy" */
"style-loader?{'injectType':'styleTag','attributes':{'data-theme':'theme-dark'}}!./theme-dark.scss"
)
Explanation:
We are using the style-loader with inline loader syntax to parse the file with some helpful arguments:injectType: 'styleTag'
it will make Webpack insert the generated CSS into a style tag inside the HTML head. This attributes:{'data-theme':''} is to insert an attribute in a style tag that will be used to identify the theme.
The library will also search for link[href*=theme-${theme}]:not([rel="prefetch"])
, link tag that have on href theme-* who isen't a prefetch link.
For use this will can use the webpack magic comment /* webpackChunkName: "theme-dark" */
.
you need the add a comment in your theme file like:
/**@theme:dark*/
Imediataly after load an theme, the library will find the inserted style tag that contains this comment pattern and insert the attribute data-theme
.
import lazyThemeChanger from 'lazy-theme-changer';
const themes = {
dark: () => import(
/* webpackChunkName: "theme-dark" */
/* webpackMode: "lazy" */
'./theme-dark.scss'
),
light: () => import(
/* webpackChunkName: "theme-light" */
/* webpackMode: "lazy" */
'./theme-light.scss'
),
};
const changeTheme = lazyThemeChanger(themes)
changeTheme('dark')