Skip to content

Instantly share code, notes, and snippets.

@bwindels
Created April 8, 2022 15:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bwindels/3ebbfc443c6c9a203dd8321d109f21b0 to your computer and use it in GitHub Desktop.
Save bwindels/3ebbfc443c6c9a203dd8321d109f21b0 to your computer and use it in GitHub Desktop.
Sample project how to load theme at dev time
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<script type="module">
import "@theme/default";
</script>
</head>
<body>
hello!
</body>
</html>
{
"name": "vite-resolve-dev-test",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"devDependencies": {
"vite": "^2.9.1"
}
}
body {
color: var(--fg-color);
background-color: var(--bg-color);
}
const {defineConfig} = require('vite');
const path = require('path');
const virtualModuleId = '@theme/'
const resolvedVirtualModuleId = '\0' + virtualModuleId;
const examplePlugin = () => {
return {
name: 'test-css-import',
async resolveId(id, importer, options) {
if (id.startsWith(virtualModuleId)) {
return `\0` + id;
}
},
async load(id) {
if (id.startsWith(resolvedVirtualModuleId)) {
let [theme, variant, file] = id.substr(resolvedVirtualModuleId.length).split("/");
if (theme === "default") {
theme = "foo";
}
if (!variant || variant === "default") {
variant = "light";
}
if (!file) {
file = "index.js";
}
switch (file) {
case "index.js":
return `import "${path.resolve(`./theme-${theme}.css`)}";` +
`import "@theme/${theme}/${variant}/variables.css"`;
case "variables.css":
return `:root {--fg-color: ${ variant === "light" ? "green" : "lightgreen"}; --bg-color: ${ variant === "light" ? "white" : "black"};}`;
}
}
}
}
}
export default defineConfig(({mode}) => {
return {
plugins: [examplePlugin()],
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment