@unocss/vite 0.30.12 → 0.30.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -40,27 +40,40 @@ This mode enables a set of Vite plugins for `build` and for `dev` with `HMR` sup
40
40
 
41
41
  The generated `css` will be a global stylesheet injected on the `index.html`.
42
42
 
43
- ### vue-scoped (WIP)
43
+ ### vue-scoped
44
44
 
45
45
  This mode will inject generated CSS to Vue SFC's `<style scoped>` for isolation.
46
46
 
47
- ### svelte-scoped (WIP)
47
+ ### svelte-scoped
48
48
 
49
49
  This mode will inject generated CSS to Svelte's `<style>` for isolation.
50
50
 
51
- ### per-module (WIP)
51
+ ### shadow-dom
52
+
53
+ Since `Web Components` uses `Shadow DOM`, there is no way to style content directly from a global stylesheet (unless you use `custom css vars`, those will penetrate the `Shadow DOM`), you need to inline the generated css by the plugin into the `Shadow DOM` style.
54
+
55
+ To inline the generated css, you only need to configure the plugin mode to `shadow-dom` and include `@unocss-placeholder` magic placeholder on each web component style css block.
56
+
57
+ ### per-module (Experimental)
52
58
 
53
59
  This mode will generate a CSS sheet for each module, can be scoped.
54
60
 
55
- ### dist-chunk (WIP)
61
+ ### dist-chunk (Experimental)
56
62
 
57
63
  This mode will generate a CSS sheet for each code chunk on build, great for MPA.
58
64
 
59
- ### shadow-dom
65
+ ## "Design in DevTools"
60
66
 
61
- Since `Web Components` uses `Shadow DOM`, there is no way to style content directly from a global stylesheet (unless you use `custom css vars`, those will penetrate the `Shadow DOM`), you need to inline the generated css by the plugin into the `Shadow DOM` style.
67
+ Because of limitation of "on-demand" where the DevTools don't know those you haven't used in your source code yet. So if you want to try how things work by directly changing the classes in DevTools, just add the following lines to your main entry.
62
68
 
63
- To inline the generated css, you only need to configure the plugin mode to `shadow-dom` and include `@unocss-placeholder` magic placeholder on each web component style css block.
69
+ ```ts
70
+ import 'uno.css'
71
+ import 'virtual:unocss-devtools'
72
+ ```
73
+
74
+ > ⚠️ Please use it with caution, under the hood we use [`MutationObserver`](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) to detect the class changes. Which means not only your manual changes but also the changes made by your scripts will be detected and included in the stylesheet. This could cause some misalignment between dev and the production build when you add dynamic classes based on some logic in script tags. We recommended adding your dynamic parts to the [safelist](https://github.com/unocss/unocss/issues/511) or setup UI regression tests for your production build if possible.
75
+
76
+ `virtual:unocss-devtools` will be an empty bundle in production.
64
77
 
65
78
  ## Frameworks
66
79
 
@@ -0,0 +1,46 @@
1
+ 'use strict';
2
+
3
+ function post(data) {
4
+ return fetch("__POST_PATH__", {
5
+ method: "POST",
6
+ headers: {
7
+ "Content-Type": "application/json"
8
+ },
9
+ body: JSON.stringify(data)
10
+ });
11
+ }
12
+ function include(set, v) {
13
+ for (const i of v)
14
+ set.add(i);
15
+ }
16
+ console.log("%c[unocss] devtools support enabled %c\nread more at https://windicss.org", "background:#0ea5e9; color:white; padding: 1px 4px; border-radius: 3px;", "");
17
+ const visitedClasses = /* @__PURE__ */ new Set();
18
+ const pendingClasses = /* @__PURE__ */ new Set();
19
+ let _timer;
20
+ function schedule() {
21
+ if (_timer != null)
22
+ clearTimeout(_timer);
23
+ _timer = setTimeout(() => {
24
+ if (pendingClasses.size) {
25
+ post({ type: "add-classes", data: Array.from(pendingClasses) });
26
+ include(visitedClasses, pendingClasses);
27
+ pendingClasses.clear();
28
+ }
29
+ }, 10);
30
+ }
31
+ const mutationObserver = new MutationObserver((mutations) => {
32
+ mutations.forEach((mutation) => {
33
+ if (mutation.attributeName === "class" && mutation.target) {
34
+ Array.from(mutation.target.classList || []).forEach((i) => {
35
+ if (!visitedClasses.has(i))
36
+ pendingClasses.add(i);
37
+ });
38
+ schedule();
39
+ }
40
+ });
41
+ });
42
+ mutationObserver.observe(document.documentElement || document.body, {
43
+ childList: true,
44
+ subtree: true,
45
+ attributes: true
46
+ });
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,44 @@
1
+ function post(data) {
2
+ return fetch("__POST_PATH__", {
3
+ method: "POST",
4
+ headers: {
5
+ "Content-Type": "application/json"
6
+ },
7
+ body: JSON.stringify(data)
8
+ });
9
+ }
10
+ function include(set, v) {
11
+ for (const i of v)
12
+ set.add(i);
13
+ }
14
+ console.log("%c[unocss] devtools support enabled %c\nread more at https://windicss.org", "background:#0ea5e9; color:white; padding: 1px 4px; border-radius: 3px;", "");
15
+ const visitedClasses = /* @__PURE__ */ new Set();
16
+ const pendingClasses = /* @__PURE__ */ new Set();
17
+ let _timer;
18
+ function schedule() {
19
+ if (_timer != null)
20
+ clearTimeout(_timer);
21
+ _timer = setTimeout(() => {
22
+ if (pendingClasses.size) {
23
+ post({ type: "add-classes", data: Array.from(pendingClasses) });
24
+ include(visitedClasses, pendingClasses);
25
+ pendingClasses.clear();
26
+ }
27
+ }, 10);
28
+ }
29
+ const mutationObserver = new MutationObserver((mutations) => {
30
+ mutations.forEach((mutation) => {
31
+ if (mutation.attributeName === "class" && mutation.target) {
32
+ Array.from(mutation.target.classList || []).forEach((i) => {
33
+ if (!visitedClasses.has(i))
34
+ pendingClasses.add(i);
35
+ });
36
+ schedule();
37
+ }
38
+ });
39
+ });
40
+ mutationObserver.observe(document.documentElement || document.body, {
41
+ childList: true,
42
+ subtree: true,
43
+ attributes: true
44
+ });
package/dist/index.cjs CHANGED
@@ -8,11 +8,15 @@ const config = require('@unocss/config');
8
8
  const core = require('@unocss/core');
9
9
  const crypto = require('crypto');
10
10
  const MagicString = require('magic-string');
11
+ const fs = require('fs');
12
+ const path = require('path');
13
+ const url = require('url');
11
14
 
12
15
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e["default"] : e; }
13
16
 
14
17
  const UnocssInspector__default = /*#__PURE__*/_interopDefaultLegacy(UnocssInspector);
15
18
  const MagicString__default = /*#__PURE__*/_interopDefaultLegacy(MagicString);
19
+ const fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
16
20
 
17
21
  const regexCssId = /\.(css|postcss|sass|scss|less|stylus|styl)$/;
18
22
  const defaultExclude = [regexCssId];
@@ -690,6 +694,133 @@ function initTransformerPlugins(ctx) {
690
694
  ];
691
695
  }
692
696
 
697
+ const _dirname = typeof __dirname !== "undefined" ? __dirname : path.dirname(url.fileURLToPath((typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('index.cjs', document.baseURI).href))));
698
+ const DEVTOOLS_MODULE_ID = "virtual:unocss-devtools";
699
+ const MOCK_CLASSES_MODULE_ID = "virtual:unocss-mock-classes";
700
+ const MOCK_CLASSES_PATH = "/@unocss/mock-classes";
701
+ const DEVTOOLS_PATH = "/@unocss/devtools";
702
+ const DEVTOOLS_CSS_PATH = "/@unocss/devtools.css";
703
+ const devtoolCss = /* @__PURE__ */ new Set();
704
+ const MODULES_MAP = {
705
+ [DEVTOOLS_MODULE_ID]: DEVTOOLS_PATH,
706
+ [MOCK_CLASSES_MODULE_ID]: MOCK_CLASSES_PATH
707
+ };
708
+ const POST_PATH = "/@unocss-devtools-update";
709
+ function getBodyJson(req) {
710
+ return new Promise((resolve2, reject) => {
711
+ let body = "";
712
+ req.on("data", (chunk) => body += chunk);
713
+ req.on("error", reject);
714
+ req.on("end", () => {
715
+ try {
716
+ resolve2(JSON.parse(body) || {});
717
+ } catch (e) {
718
+ reject(e);
719
+ }
720
+ });
721
+ });
722
+ }
723
+ function createDevtoolsPlugin(ctx) {
724
+ let config;
725
+ let server;
726
+ let clientCode = "";
727
+ let devtoolTimer;
728
+ let lastUpdate = Date.now();
729
+ function toClass(name) {
730
+ return `${core.toEscapedSelector(name)}{}`;
731
+ }
732
+ function updateDevtoolClass() {
733
+ clearTimeout(devtoolTimer);
734
+ devtoolTimer = setTimeout(() => {
735
+ lastUpdate = Date.now();
736
+ if (!server)
737
+ return;
738
+ const mod = server.moduleGraph.getModuleById(DEVTOOLS_CSS_PATH);
739
+ if (!mod)
740
+ return;
741
+ server.moduleGraph.invalidateModule(mod);
742
+ server.ws.send({
743
+ type: "update",
744
+ updates: [{
745
+ acceptedPath: DEVTOOLS_CSS_PATH,
746
+ path: DEVTOOLS_CSS_PATH,
747
+ timestamp: lastUpdate,
748
+ type: "js-update"
749
+ }]
750
+ });
751
+ }, 100);
752
+ }
753
+ async function getMockClassesInjector() {
754
+ const suggest = Object.keys(ctx.uno.config.rulesStaticMap);
755
+ const comment = "/* unocss CSS mock class names for devtools auto-completion */\n";
756
+ const css = suggest.map(toClass).join("");
757
+ return `
758
+ const style = document.createElement('style')
759
+ style.setAttribute('type', 'text/css')
760
+ style.innerHTML = ${JSON.stringify(comment + css)}
761
+ document.head.prepend(style)
762
+ `;
763
+ }
764
+ return [
765
+ {
766
+ name: "unocss:devtools",
767
+ configResolved(_config) {
768
+ config = _config;
769
+ },
770
+ configureServer(_server) {
771
+ server = _server;
772
+ server.middlewares.use(async (req, res, next) => {
773
+ if (req.url !== POST_PATH)
774
+ return next();
775
+ try {
776
+ const data = await getBodyJson(req);
777
+ const type = data?.type;
778
+ let changed = false;
779
+ switch (type) {
780
+ case "add-classes":
781
+ data.data.forEach((key) => {
782
+ if (!devtoolCss.has(key)) {
783
+ devtoolCss.add(key);
784
+ changed = true;
785
+ }
786
+ });
787
+ if (changed)
788
+ updateDevtoolClass();
789
+ }
790
+ res.statusCode = 200;
791
+ } catch (e) {
792
+ console.error(e);
793
+ res.statusCode = 500;
794
+ }
795
+ res.end();
796
+ });
797
+ },
798
+ resolveId(id) {
799
+ if (id === DEVTOOLS_CSS_PATH)
800
+ return DEVTOOLS_CSS_PATH;
801
+ return MODULES_MAP[id];
802
+ },
803
+ async load(id) {
804
+ if (id === DEVTOOLS_PATH) {
805
+ if (!clientCode) {
806
+ clientCode = [
807
+ await fs__default.promises.readFile(path.resolve(_dirname, "client.mjs"), "utf-8"),
808
+ `import('${MOCK_CLASSES_MODULE_ID}')`,
809
+ `import('${DEVTOOLS_CSS_PATH}')`
810
+ ].join("\n").replace("__POST_PATH__", (config.server?.origin ?? "") + POST_PATH);
811
+ }
812
+ return config.command === "build" ? "" : clientCode;
813
+ } else if (id === MOCK_CLASSES_PATH) {
814
+ return await getMockClassesInjector();
815
+ } else if (id === DEVTOOLS_CSS_PATH) {
816
+ const { css } = await ctx.uno.generate(devtoolCss);
817
+ return css;
818
+ }
819
+ }
820
+ }
821
+ ];
822
+ }
823
+
693
824
  function defineConfig(config) {
694
825
  return config;
695
826
  }
@@ -699,6 +830,7 @@ function UnocssPlugin(configOrPath, defaults = {}) {
699
830
  const mode = inlineConfig.mode ?? "global";
700
831
  const plugins = [
701
832
  ...initTransformerPlugins(ctx),
833
+ ...createDevtoolsPlugin(ctx),
702
834
  ConfigHMRPlugin(ctx)
703
835
  ];
704
836
  if (inlineConfig.inspector !== false)
package/dist/index.mjs CHANGED
@@ -1,9 +1,12 @@
1
1
  import UnocssInspector from '@unocss/inspector';
2
2
  import { createFilter } from '@rollup/pluginutils';
3
3
  import { createConfigLoader } from '@unocss/config';
4
- import { createGenerator, BetterMap } from '@unocss/core';
4
+ import { createGenerator, BetterMap, toEscapedSelector } from '@unocss/core';
5
5
  import { createHash } from 'crypto';
6
6
  import MagicString from 'magic-string';
7
+ import fs from 'fs';
8
+ import { resolve, dirname } from 'path';
9
+ import { fileURLToPath } from 'url';
7
10
 
8
11
  const regexCssId = /\.(css|postcss|sass|scss|less|stylus|styl)$/;
9
12
  const defaultExclude = [regexCssId];
@@ -681,6 +684,133 @@ function initTransformerPlugins(ctx) {
681
684
  ];
682
685
  }
683
686
 
687
+ const _dirname = typeof __dirname !== "undefined" ? __dirname : dirname(fileURLToPath(import.meta.url));
688
+ const DEVTOOLS_MODULE_ID = "virtual:unocss-devtools";
689
+ const MOCK_CLASSES_MODULE_ID = "virtual:unocss-mock-classes";
690
+ const MOCK_CLASSES_PATH = "/@unocss/mock-classes";
691
+ const DEVTOOLS_PATH = "/@unocss/devtools";
692
+ const DEVTOOLS_CSS_PATH = "/@unocss/devtools.css";
693
+ const devtoolCss = /* @__PURE__ */ new Set();
694
+ const MODULES_MAP = {
695
+ [DEVTOOLS_MODULE_ID]: DEVTOOLS_PATH,
696
+ [MOCK_CLASSES_MODULE_ID]: MOCK_CLASSES_PATH
697
+ };
698
+ const POST_PATH = "/@unocss-devtools-update";
699
+ function getBodyJson(req) {
700
+ return new Promise((resolve2, reject) => {
701
+ let body = "";
702
+ req.on("data", (chunk) => body += chunk);
703
+ req.on("error", reject);
704
+ req.on("end", () => {
705
+ try {
706
+ resolve2(JSON.parse(body) || {});
707
+ } catch (e) {
708
+ reject(e);
709
+ }
710
+ });
711
+ });
712
+ }
713
+ function createDevtoolsPlugin(ctx) {
714
+ let config;
715
+ let server;
716
+ let clientCode = "";
717
+ let devtoolTimer;
718
+ let lastUpdate = Date.now();
719
+ function toClass(name) {
720
+ return `${toEscapedSelector(name)}{}`;
721
+ }
722
+ function updateDevtoolClass() {
723
+ clearTimeout(devtoolTimer);
724
+ devtoolTimer = setTimeout(() => {
725
+ lastUpdate = Date.now();
726
+ if (!server)
727
+ return;
728
+ const mod = server.moduleGraph.getModuleById(DEVTOOLS_CSS_PATH);
729
+ if (!mod)
730
+ return;
731
+ server.moduleGraph.invalidateModule(mod);
732
+ server.ws.send({
733
+ type: "update",
734
+ updates: [{
735
+ acceptedPath: DEVTOOLS_CSS_PATH,
736
+ path: DEVTOOLS_CSS_PATH,
737
+ timestamp: lastUpdate,
738
+ type: "js-update"
739
+ }]
740
+ });
741
+ }, 100);
742
+ }
743
+ async function getMockClassesInjector() {
744
+ const suggest = Object.keys(ctx.uno.config.rulesStaticMap);
745
+ const comment = "/* unocss CSS mock class names for devtools auto-completion */\n";
746
+ const css = suggest.map(toClass).join("");
747
+ return `
748
+ const style = document.createElement('style')
749
+ style.setAttribute('type', 'text/css')
750
+ style.innerHTML = ${JSON.stringify(comment + css)}
751
+ document.head.prepend(style)
752
+ `;
753
+ }
754
+ return [
755
+ {
756
+ name: "unocss:devtools",
757
+ configResolved(_config) {
758
+ config = _config;
759
+ },
760
+ configureServer(_server) {
761
+ server = _server;
762
+ server.middlewares.use(async (req, res, next) => {
763
+ if (req.url !== POST_PATH)
764
+ return next();
765
+ try {
766
+ const data = await getBodyJson(req);
767
+ const type = data?.type;
768
+ let changed = false;
769
+ switch (type) {
770
+ case "add-classes":
771
+ data.data.forEach((key) => {
772
+ if (!devtoolCss.has(key)) {
773
+ devtoolCss.add(key);
774
+ changed = true;
775
+ }
776
+ });
777
+ if (changed)
778
+ updateDevtoolClass();
779
+ }
780
+ res.statusCode = 200;
781
+ } catch (e) {
782
+ console.error(e);
783
+ res.statusCode = 500;
784
+ }
785
+ res.end();
786
+ });
787
+ },
788
+ resolveId(id) {
789
+ if (id === DEVTOOLS_CSS_PATH)
790
+ return DEVTOOLS_CSS_PATH;
791
+ return MODULES_MAP[id];
792
+ },
793
+ async load(id) {
794
+ if (id === DEVTOOLS_PATH) {
795
+ if (!clientCode) {
796
+ clientCode = [
797
+ await fs.promises.readFile(resolve(_dirname, "client.mjs"), "utf-8"),
798
+ `import('${MOCK_CLASSES_MODULE_ID}')`,
799
+ `import('${DEVTOOLS_CSS_PATH}')`
800
+ ].join("\n").replace("__POST_PATH__", (config.server?.origin ?? "") + POST_PATH);
801
+ }
802
+ return config.command === "build" ? "" : clientCode;
803
+ } else if (id === MOCK_CLASSES_PATH) {
804
+ return await getMockClassesInjector();
805
+ } else if (id === DEVTOOLS_CSS_PATH) {
806
+ const { css } = await ctx.uno.generate(devtoolCss);
807
+ return css;
808
+ }
809
+ }
810
+ }
811
+ ];
812
+ }
813
+
684
814
  function defineConfig(config) {
685
815
  return config;
686
816
  }
@@ -690,6 +820,7 @@ function UnocssPlugin(configOrPath, defaults = {}) {
690
820
  const mode = inlineConfig.mode ?? "global";
691
821
  const plugins = [
692
822
  ...initTransformerPlugins(ctx),
823
+ ...createDevtoolsPlugin(ctx),
693
824
  ConfigHMRPlugin(ctx)
694
825
  ];
695
826
  if (inlineConfig.inspector !== false)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@unocss/vite",
3
- "version": "0.30.12",
3
+ "version": "0.30.13",
4
4
  "description": "The Vite plugin for UnoCSS",
5
5
  "keywords": [
6
6
  "unocss",
@@ -27,6 +27,11 @@
27
27
  "require": "./dist/index.cjs",
28
28
  "import": "./dist/index.mjs",
29
29
  "types": "./dist/index.d.ts"
30
+ },
31
+ "./client": {
32
+ "import": "./dist/client.mjs",
33
+ "require": "./dist/client.js",
34
+ "types": "./dist/client.d.ts"
30
35
  }
31
36
  },
32
37
  "files": [
@@ -35,11 +40,11 @@
35
40
  "sideEffects": false,
36
41
  "dependencies": {
37
42
  "@rollup/pluginutils": "^4.2.0",
38
- "@unocss/config": "0.30.12",
39
- "@unocss/core": "0.30.12",
40
- "@unocss/inspector": "0.30.12",
41
- "@unocss/scope": "0.30.12",
42
- "@unocss/transformer-directives": "0.30.12",
43
+ "@unocss/config": "0.30.13",
44
+ "@unocss/core": "0.30.13",
45
+ "@unocss/inspector": "0.30.13",
46
+ "@unocss/scope": "0.30.13",
47
+ "@unocss/transformer-directives": "0.30.13",
43
48
  "magic-string": "^0.26.1"
44
49
  },
45
50
  "devDependencies": {
@@ -49,5 +54,5 @@
49
54
  "build": "unbuild",
50
55
  "stub": "unbuild --stub"
51
56
  },
52
- "readme": "# @unocss/vite\n\nThe Vite plugin for UnoCSS. Ships with the `unocss` package.\n\n> This plugin does not come with any default presets. You are building a meta framework on top of UnoCSS, see [this file](https://github.com/unocss/unocss/blob/main/packages/unocss/src/vite.ts) for an example to bind the default presets.\n\n## Installation\n\n```bash\nnpm i -D unocss\n```\n\n```ts\n// vite.config.ts\nimport Unocss from 'unocss/vite'\n\nexport default {\n plugins: [\n Unocss({ /* options */ }),\n ],\n}\n```\n\nAdd `uno.css` to your main entry:\n\n```ts\n// main.ts\nimport 'uno.css'\n```\n\n## Modes\n\nThe Vite plugin comes with a set of modes that enable different behaviors.\n\n### global (default)\n\nThis is the default mode for the plugin: in this mode you need to add the import of `uno.css` on your entry point.\n\nThis mode enables a set of Vite plugins for `build` and for `dev` with `HMR` support.\n\nThe generated `css` will be a global stylesheet injected on the `index.html`.\n\n### vue-scoped (WIP)\n\nThis mode will inject generated CSS to Vue SFC's `<style scoped>` for isolation.\n\n### svelte-scoped (WIP)\n\nThis mode will inject generated CSS to Svelte's `<style>` for isolation.\n\n### per-module (WIP)\n\nThis mode will generate a CSS sheet for each module, can be scoped.\n\n### dist-chunk (WIP)\n\nThis mode will generate a CSS sheet for each code chunk on build, great for MPA.\n\n### shadow-dom\n\nSince `Web Components` uses `Shadow DOM`, there is no way to style content directly from a global stylesheet (unless you use `custom css vars`, those will penetrate the `Shadow DOM`), you need to inline the generated css by the plugin into the `Shadow DOM` style.\n\nTo inline the generated css, you only need to configure the plugin mode to `shadow-dom` and include `@unocss-placeholder` magic placeholder on each web component style css block.\n\n## Frameworks\n\nSome UI/App frameworks have some caveats that must be fixed to make it work, if you're using one of the following frameworks, just apply the suggestions.\n\n### React\n\n**WARNING**: You should import the `uno.css` virtual module using `import 'virtual:uno.css'` instead `import 'uno.css'`. When you start the dev server first time, you'll need to update some style module to get it working (we're trying to fix it).\n\nIf you're using `@vitejs/plugin-react`:\n\n```ts\n// vite.config.js\nimport react from '@vitejs/plugin-react'\nimport Unocss from 'unocss/vite'\n\nexport default {\n plugins: [\n react(),\n Unocss({\n /* options */\n }),\n ],\n}\n```\n\nor if you're using `@vitejs/plugin-react-refresh`:\n\n```ts\n// vite.config.js\nimport reactRefresh from '@vitejs/plugin-react-refresh'\nimport Unocss from 'unocss/vite'\n\nexport default {\n plugins: [\n reactRefresh(),\n Unocss({\n /* options */\n }),\n ],\n}\n```\n\nIf you're using `@unocss/preset-attributify` you should remove `tsc` from the `build` script.\n\nIf you are using `@vitejs/plugin-react` with `@unocss/preset-attributify`, you must add the plugin before `@vitejs/plugin-react`.\n\n```ts\n// vite.config.js\nimport react from '@vitejs/plugin-react'\nimport Unocss from 'unocss/vite'\n\nexport default {\n plugins: [\n Unocss({\n /* options */\n }),\n react(),\n ],\n}\n```\n\nYou have a `React` example project on [examples/vite-react](https://github.com/unocss/unocss/tree/main/examples/vite-react) directory using both plugins, check the scripts on `package.json` and its Vite configuration file.\n\n### Preact\n\nIf you're using `@preact/preset-vite`:\n\n```ts\n// vite.config.js\nimport preact from '@preact/preset-vite'\nimport Unocss from 'unocss/vite'\n\nexport default {\n plugins: [\n preact(),\n Unocss({\n /* options */\n }),\n ],\n}\n```\n\nor if you're using `@prefresh/vite`:\n\n```ts\n// vite.config.js\nimport prefresh from '@prefresh/vite'\nimport Unocss from 'unocss/vite'\n\nexport default {\n plugins: [\n prefresh(),\n Unocss({\n /* options */\n }),\n ],\n}\n```\n\nIf you're using `@unocss/preset-attributify` you should remove `tsc` from the `build` script.\n\nIf you are using `@preact/preset-vite` with `@unocss/preset-attributify`, you must add the plugin before `@preact/preset-vite`.\n\n```ts\n// vite.config.js\nimport preact from '@preact/preset-vite'\nimport Unocss from 'unocss/vite'\n\nexport default {\n plugins: [\n Unocss({\n /* options */\n }),\n preact(),\n ],\n}\n```\n\nYou have a `Preact` example project on [examples/vite-preact](https://github.com/unocss/unocss/tree/main/examples/vite-preact) directory using both plugins, check the scripts on `package.json` and its Vite configuration file.\n\n### Svelte\n\nYou must add the plugin before `@sveltejs/vite-plugin-svelte`.\n\nTo support `class:foo` and `class:foo={bar}` add the plugin and configure `extractorSvelte` on `extractors` option.\n\nYou can use simple rules with `class:`, for example `class:bg-red-500={foo}` or using `shorcuts` to include multiples rules, see `src/App.svelte` on linked example project bellow.\n\n```ts\n// vite.config.js\nimport { svelte } from '@sveltejs/vite-plugin-svelte'\nimport Unocss from 'unocss/vite'\nimport { extractorSvelte } from '@unocss/core'\n\nexport default {\n plugins: [\n Unocss({\n extractors: [extractorSvelte],\n /* more options */\n }),\n svelte(),\n ],\n}\n```\n\nYou have a `Vite + Svelte` example project on [examples/vite-svelte](https://github.com/unocss/unocss/tree/main/examples/vite-svelte) directory.\n\n### Sveltekit\n\nTo support `class:foo` and `class:foo={bar}` add the plugin and configure `extractorSvelte` on `extractors` option.\n\nYou can use simple rules with `class:`, for example `class:bg-red-500={foo}` or using `shorcuts` to include multiples rules, see `src/routes/__layout.svelte` on linked example project bellow.\n\n```ts\n// svelte.config.js\nimport preprocess from 'svelte-preprocess'\nimport UnoCss from 'unocss/vite'\nimport { extractorSvelte } from '@unocss/core'\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n // Consult https://github.com/sveltejs/svelte-preprocess\n // for more information about preprocessors\n preprocess: preprocess(),\n kit: {\n vite: {\n plugins: [\n UnoCss({\n extractors: [extractorSvelte],\n /* more options */\n }),\n ],\n },\n },\n}\n```\n\nYou have a `SvelteKit` example project on [examples/sveltekit](https://github.com/unocss/unocss/tree/main/examples/sveltekit) directory.\n\n### Web Components\n\nTo work with web components you need to enable `shadow-dom` mode on the plugin.\n\nDon't forget to remove the import for `uno.css` since the `shadow-dom` mode will not expose it and the application will not work.\n\n```ts\n// vite.config.js\nimport Unocss from 'unocss/vite'\n\nexport default {\n plugins: [\n Unocss({\n mode: 'shadow-dom',\n /* more options */\n }),\n ],\n}\n```\n\nOn each `web component` just add `@unocss-placeholder` to its style css block:\n```ts\nconst template = document.createElement('template')\ntemplate.innerHTML = `\n<style>\n:host {...}\n@unocss-placeholder\n</style>\n<div class=\"m-1em\">\n...\n</div>\n`\n```\n\nIf you're using [Lit](https://lit.dev/):\n\n```ts\n@customElement('my-element')\nexport class MyElement extends LitElement {\n static styles = css`\n :host {...}\n @unocss-placeholder\n `\n ...\n}\n```\n\nYou have a `Web Components` example project on [examples/vite-lit](https://github.com/unocss/unocss/tree/main/examples/vite-lit) directory.\n\n#### `::part` built-in support\n\nYou can use `::part` since the plugin supports it via `shortcuts` and using `part-[<part-name>]:<rule|shortcut>` rule from `preset-mini`, for example using it with simple rules like `part-[<part-name>]:bg-green-500` or using some `shortcut`: check `src/my-element.ts` on linked example project bellow.\n\nThe `part-[<part-name>]:<rule|shortcut>` will work only with this plugin using the `shadow-dom` mode.\n\nThe plugin uses `nth-of-type` to avoid collisions with multiple parts in the same web component and for the same parts on distinct web components, you don't need to worry about it, the plugin will take care for you.\n\n```ts\n// vite.config.js\nimport Unocss from 'unocss/vite'\n\nexport default {\n plugins: [\n Unocss({\n mode: 'shadow-dom',\n shortcuts: [\n { 'cool-blue': 'bg-blue-500 text-white' },\n { 'cool-green': 'bg-green-500 text-black' },\n ],\n /* more options */\n }),\n ],\n}\n```\n\nthen in your web components:\n\n```ts\n// my-container-wc.ts\nconst template = document.createElement('template')\ntemplate.innerHTML = `\n<style>\n@unocss-placeholder\n</style>\n<my-wc-with-parts class=\"part-[cool-part]:cool-blue part-[another-cool-part]:cool-green\">...</my-wc-with-parts>\n`\n```\n\n```ts\n// my-wc-with-parts.ts\nconst template = document.createElement('template')\ntemplate.innerHTML = `\n<style>\n@unocss-placeholder\n</style>\n<div>\n <div part=\"cool-part\">...</div>\n <div part=\"another-cool-part\">...</div>\n</div>\n`\n```\n\n### Solid\n\n**WARNING**: You should import the `uno.css` virtual module using `import 'virtual:uno.css'` instead `import 'uno.css'`. When you start the dev server first time, you'll need to update some style module to get it working (we're trying to fix it).\n\n```ts\n// vite.config.js\nimport solidPlugin from 'vite-plugin-solid'\nimport Unocss from 'unocss/vite'\n\nexport default {\n plugins: [\n solidPlugin(),\n Unocss({\n /* options */\n }),\n ],\n}\n```\n\nYou have a `Vite + Solid` example project on [examples/vite-solid](https://github.com/unocss/unocss/tree/main/examples/vite-solid) directory.\n\n### Elm\n\nYou need to add the `vite-plugin-elm` plugin before UnoCSS's plugin.\n\n```ts\n// vite.config.js\nimport { defineConfig } from 'vite'\nimport elmPlugin from 'vite-plugin-elm'\nimport Unocss from 'unocss/vite'\n\nexport default defineConfig({\n plugins: [\n elmPlugin(),\n Unocss({\n /* options */\n }),\n ],\n})\n```\n\nYou have a `Vite + Elm` example project on [examples/vite-elm](https://github.com/unocss/unocss/tree/main/examples/vite-elm) directory.\n\n## License\n\nMIT License © 2021-PRESENT [Anthony Fu](https://github.com/antfu)\n"
57
+ "readme": "# @unocss/vite\n\nThe Vite plugin for UnoCSS. Ships with the `unocss` package.\n\n> This plugin does not come with any default presets. You are building a meta framework on top of UnoCSS, see [this file](https://github.com/unocss/unocss/blob/main/packages/unocss/src/vite.ts) for an example to bind the default presets.\n\n## Installation\n\n```bash\nnpm i -D unocss\n```\n\n```ts\n// vite.config.ts\nimport Unocss from 'unocss/vite'\n\nexport default {\n plugins: [\n Unocss({ /* options */ }),\n ],\n}\n```\n\nAdd `uno.css` to your main entry:\n\n```ts\n// main.ts\nimport 'uno.css'\n```\n\n## Modes\n\nThe Vite plugin comes with a set of modes that enable different behaviors.\n\n### global (default)\n\nThis is the default mode for the plugin: in this mode you need to add the import of `uno.css` on your entry point.\n\nThis mode enables a set of Vite plugins for `build` and for `dev` with `HMR` support.\n\nThe generated `css` will be a global stylesheet injected on the `index.html`.\n\n### vue-scoped\n\nThis mode will inject generated CSS to Vue SFC's `<style scoped>` for isolation.\n\n### svelte-scoped\n\nThis mode will inject generated CSS to Svelte's `<style>` for isolation.\n\n### shadow-dom\n\nSince `Web Components` uses `Shadow DOM`, there is no way to style content directly from a global stylesheet (unless you use `custom css vars`, those will penetrate the `Shadow DOM`), you need to inline the generated css by the plugin into the `Shadow DOM` style.\n\nTo inline the generated css, you only need to configure the plugin mode to `shadow-dom` and include `@unocss-placeholder` magic placeholder on each web component style css block.\n\n### per-module (Experimental)\n\nThis mode will generate a CSS sheet for each module, can be scoped.\n\n### dist-chunk (Experimental)\n\nThis mode will generate a CSS sheet for each code chunk on build, great for MPA.\n\n## \"Design in DevTools\"\n\nBecause of limitation of \"on-demand\" where the DevTools don't know those you haven't used in your source code yet. So if you want to try how things work by directly changing the classes in DevTools, just add the following lines to your main entry.\n\n```ts\nimport 'uno.css'\nimport 'virtual:unocss-devtools'\n```\n\n> ⚠️ Please use it with caution, under the hood we use [`MutationObserver`](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) to detect the class changes. Which means not only your manual changes but also the changes made by your scripts will be detected and included in the stylesheet. This could cause some misalignment between dev and the production build when you add dynamic classes based on some logic in script tags. We recommended adding your dynamic parts to the [safelist](https://github.com/unocss/unocss/issues/511) or setup UI regression tests for your production build if possible.\n\n`virtual:unocss-devtools` will be an empty bundle in production.\n\n## Frameworks\n\nSome UI/App frameworks have some caveats that must be fixed to make it work, if you're using one of the following frameworks, just apply the suggestions.\n\n### React\n\n**WARNING**: You should import the `uno.css` virtual module using `import 'virtual:uno.css'` instead `import 'uno.css'`. When you start the dev server first time, you'll need to update some style module to get it working (we're trying to fix it).\n\nIf you're using `@vitejs/plugin-react`:\n\n```ts\n// vite.config.js\nimport react from '@vitejs/plugin-react'\nimport Unocss from 'unocss/vite'\n\nexport default {\n plugins: [\n react(),\n Unocss({\n /* options */\n }),\n ],\n}\n```\n\nor if you're using `@vitejs/plugin-react-refresh`:\n\n```ts\n// vite.config.js\nimport reactRefresh from '@vitejs/plugin-react-refresh'\nimport Unocss from 'unocss/vite'\n\nexport default {\n plugins: [\n reactRefresh(),\n Unocss({\n /* options */\n }),\n ],\n}\n```\n\nIf you're using `@unocss/preset-attributify` you should remove `tsc` from the `build` script.\n\nIf you are using `@vitejs/plugin-react` with `@unocss/preset-attributify`, you must add the plugin before `@vitejs/plugin-react`.\n\n```ts\n// vite.config.js\nimport react from '@vitejs/plugin-react'\nimport Unocss from 'unocss/vite'\n\nexport default {\n plugins: [\n Unocss({\n /* options */\n }),\n react(),\n ],\n}\n```\n\nYou have a `React` example project on [examples/vite-react](https://github.com/unocss/unocss/tree/main/examples/vite-react) directory using both plugins, check the scripts on `package.json` and its Vite configuration file.\n\n### Preact\n\nIf you're using `@preact/preset-vite`:\n\n```ts\n// vite.config.js\nimport preact from '@preact/preset-vite'\nimport Unocss from 'unocss/vite'\n\nexport default {\n plugins: [\n preact(),\n Unocss({\n /* options */\n }),\n ],\n}\n```\n\nor if you're using `@prefresh/vite`:\n\n```ts\n// vite.config.js\nimport prefresh from '@prefresh/vite'\nimport Unocss from 'unocss/vite'\n\nexport default {\n plugins: [\n prefresh(),\n Unocss({\n /* options */\n }),\n ],\n}\n```\n\nIf you're using `@unocss/preset-attributify` you should remove `tsc` from the `build` script.\n\nIf you are using `@preact/preset-vite` with `@unocss/preset-attributify`, you must add the plugin before `@preact/preset-vite`.\n\n```ts\n// vite.config.js\nimport preact from '@preact/preset-vite'\nimport Unocss from 'unocss/vite'\n\nexport default {\n plugins: [\n Unocss({\n /* options */\n }),\n preact(),\n ],\n}\n```\n\nYou have a `Preact` example project on [examples/vite-preact](https://github.com/unocss/unocss/tree/main/examples/vite-preact) directory using both plugins, check the scripts on `package.json` and its Vite configuration file.\n\n### Svelte\n\nYou must add the plugin before `@sveltejs/vite-plugin-svelte`.\n\nTo support `class:foo` and `class:foo={bar}` add the plugin and configure `extractorSvelte` on `extractors` option.\n\nYou can use simple rules with `class:`, for example `class:bg-red-500={foo}` or using `shorcuts` to include multiples rules, see `src/App.svelte` on linked example project bellow.\n\n```ts\n// vite.config.js\nimport { svelte } from '@sveltejs/vite-plugin-svelte'\nimport Unocss from 'unocss/vite'\nimport { extractorSvelte } from '@unocss/core'\n\nexport default {\n plugins: [\n Unocss({\n extractors: [extractorSvelte],\n /* more options */\n }),\n svelte(),\n ],\n}\n```\n\nYou have a `Vite + Svelte` example project on [examples/vite-svelte](https://github.com/unocss/unocss/tree/main/examples/vite-svelte) directory.\n\n### Sveltekit\n\nTo support `class:foo` and `class:foo={bar}` add the plugin and configure `extractorSvelte` on `extractors` option.\n\nYou can use simple rules with `class:`, for example `class:bg-red-500={foo}` or using `shorcuts` to include multiples rules, see `src/routes/__layout.svelte` on linked example project bellow.\n\n```ts\n// svelte.config.js\nimport preprocess from 'svelte-preprocess'\nimport UnoCss from 'unocss/vite'\nimport { extractorSvelte } from '@unocss/core'\n\n/** @type {import('@sveltejs/kit').Config} */\nconst config = {\n // Consult https://github.com/sveltejs/svelte-preprocess\n // for more information about preprocessors\n preprocess: preprocess(),\n kit: {\n vite: {\n plugins: [\n UnoCss({\n extractors: [extractorSvelte],\n /* more options */\n }),\n ],\n },\n },\n}\n```\n\nYou have a `SvelteKit` example project on [examples/sveltekit](https://github.com/unocss/unocss/tree/main/examples/sveltekit) directory.\n\n### Web Components\n\nTo work with web components you need to enable `shadow-dom` mode on the plugin.\n\nDon't forget to remove the import for `uno.css` since the `shadow-dom` mode will not expose it and the application will not work.\n\n```ts\n// vite.config.js\nimport Unocss from 'unocss/vite'\n\nexport default {\n plugins: [\n Unocss({\n mode: 'shadow-dom',\n /* more options */\n }),\n ],\n}\n```\n\nOn each `web component` just add `@unocss-placeholder` to its style css block:\n```ts\nconst template = document.createElement('template')\ntemplate.innerHTML = `\n<style>\n:host {...}\n@unocss-placeholder\n</style>\n<div class=\"m-1em\">\n...\n</div>\n`\n```\n\nIf you're using [Lit](https://lit.dev/):\n\n```ts\n@customElement('my-element')\nexport class MyElement extends LitElement {\n static styles = css`\n :host {...}\n @unocss-placeholder\n `\n ...\n}\n```\n\nYou have a `Web Components` example project on [examples/vite-lit](https://github.com/unocss/unocss/tree/main/examples/vite-lit) directory.\n\n#### `::part` built-in support\n\nYou can use `::part` since the plugin supports it via `shortcuts` and using `part-[<part-name>]:<rule|shortcut>` rule from `preset-mini`, for example using it with simple rules like `part-[<part-name>]:bg-green-500` or using some `shortcut`: check `src/my-element.ts` on linked example project bellow.\n\nThe `part-[<part-name>]:<rule|shortcut>` will work only with this plugin using the `shadow-dom` mode.\n\nThe plugin uses `nth-of-type` to avoid collisions with multiple parts in the same web component and for the same parts on distinct web components, you don't need to worry about it, the plugin will take care for you.\n\n```ts\n// vite.config.js\nimport Unocss from 'unocss/vite'\n\nexport default {\n plugins: [\n Unocss({\n mode: 'shadow-dom',\n shortcuts: [\n { 'cool-blue': 'bg-blue-500 text-white' },\n { 'cool-green': 'bg-green-500 text-black' },\n ],\n /* more options */\n }),\n ],\n}\n```\n\nthen in your web components:\n\n```ts\n// my-container-wc.ts\nconst template = document.createElement('template')\ntemplate.innerHTML = `\n<style>\n@unocss-placeholder\n</style>\n<my-wc-with-parts class=\"part-[cool-part]:cool-blue part-[another-cool-part]:cool-green\">...</my-wc-with-parts>\n`\n```\n\n```ts\n// my-wc-with-parts.ts\nconst template = document.createElement('template')\ntemplate.innerHTML = `\n<style>\n@unocss-placeholder\n</style>\n<div>\n <div part=\"cool-part\">...</div>\n <div part=\"another-cool-part\">...</div>\n</div>\n`\n```\n\n### Solid\n\n**WARNING**: You should import the `uno.css` virtual module using `import 'virtual:uno.css'` instead `import 'uno.css'`. When you start the dev server first time, you'll need to update some style module to get it working (we're trying to fix it).\n\n```ts\n// vite.config.js\nimport solidPlugin from 'vite-plugin-solid'\nimport Unocss from 'unocss/vite'\n\nexport default {\n plugins: [\n solidPlugin(),\n Unocss({\n /* options */\n }),\n ],\n}\n```\n\nYou have a `Vite + Solid` example project on [examples/vite-solid](https://github.com/unocss/unocss/tree/main/examples/vite-solid) directory.\n\n### Elm\n\nYou need to add the `vite-plugin-elm` plugin before UnoCSS's plugin.\n\n```ts\n// vite.config.js\nimport { defineConfig } from 'vite'\nimport elmPlugin from 'vite-plugin-elm'\nimport Unocss from 'unocss/vite'\n\nexport default defineConfig({\n plugins: [\n elmPlugin(),\n Unocss({\n /* options */\n }),\n ],\n})\n```\n\nYou have a `Vite + Elm` example project on [examples/vite-elm](https://github.com/unocss/unocss/tree/main/examples/vite-elm) directory.\n\n## License\n\nMIT License © 2021-PRESENT [Anthony Fu](https://github.com/antfu)\n"
53
58
  }