Created
April 8, 2022 15:43
-
-
Save bwindels/3ebbfc443c6c9a203dd8321d109f21b0 to your computer and use it in GitHub Desktop.
Sample project how to load theme at dev time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "vite-resolve-dev-test", | |
"version": "1.0.0", | |
"main": "index.js", | |
"license": "MIT", | |
"devDependencies": { | |
"vite": "^2.9.1" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
body { | |
color: var(--fg-color); | |
background-color: var(--bg-color); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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