@vanilla-extract/vite-plugin 2.1.3 → 3.1.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021 SEEK
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -82,7 +82,6 @@ Want to work at a higher level while maximising style re-use? Check out 🍨 [S
82
82
  - [webpack](#webpack)
83
83
  - [esbuild](#esbuild)
84
84
  - [Vite](#vite)
85
- - [Snowpack](#snowpack)
86
85
  - [Next.js](#nextjs)
87
86
  - [Gatsby](#gatsby)
88
87
  - [Test environments](#test-environments)
@@ -95,6 +94,7 @@ Want to work at a higher level while maximising style re-use? Check out 🍨 [S
95
94
  - [createTheme](#createtheme)
96
95
  - [createGlobalTheme](#createglobaltheme)
97
96
  - [createThemeContract](#createthemecontract)
97
+ - [createGlobalThemeContract](#createglobalthemecontract)
98
98
  - [assignVars](#assignvars)
99
99
  - [createVar](#createvar)
100
100
  - [fallbackVar](#fallbackvar)
@@ -271,27 +271,6 @@ export default {
271
271
 
272
272
  > Please note: There are currently no automatic readable class names during development. However, you can still manually provide a debug ID as the last argument to functions that generate scoped styles, e.g. `export const className = style({ ... }, 'className');`
273
273
 
274
- ### Snowpack
275
-
276
- 1. Install the dependencies.
277
-
278
- ```bash
279
- npm install @vanilla-extract/css @vanilla-extract/snowpack-plugin
280
- ```
281
-
282
- 2. Add the [Snowpack](https://www.snowpack.dev/) plugin to your snowpack config.
283
-
284
- > 💡 This plugin accepts an optional [configuration object](#configuration).
285
-
286
- ```js
287
- // snowpack.config.json
288
- {
289
- "plugins": ["@vanilla-extract/snowpack-plugin"]
290
- }
291
- ```
292
-
293
- > Please note: There are currently no automatic readable class names during development. However, you can still manually provide a debug ID as the last argument to functions that generate scoped styles, e.g. `export const className = style({ ... }, 'className');`
294
-
295
274
  ### Next.js
296
275
 
297
276
  1. Install the dependencies.
@@ -300,16 +279,7 @@ npm install @vanilla-extract/css @vanilla-extract/snowpack-plugin
300
279
  npm install @vanilla-extract/css @vanilla-extract/babel-plugin @vanilla-extract/next-plugin
301
280
  ```
302
281
 
303
- 2. If you don't have a `.babelrc` file in the root of your project, create one. Add the [Babel](https://babeljs.io) plugin to your `.babelrc` file, ensuring that you're also including `"next/babel"` in your `presets` array.
304
-
305
- ```json
306
- {
307
- "presets": ["next/babel"],
308
- "plugins": ["@vanilla-extract/babel-plugin"]
309
- }
310
- ```
311
-
312
- 3. If you don't have a `next.config.js` file in the root of your project, create one. Add the [Next.js](https://nextjs.org) plugin to your `next.config.js` file.
282
+ 2. If you don't have a `next.config.js` file in the root of your project, create one. Add the [Next.js](https://nextjs.org) plugin to your `next.config.js` file.
313
283
 
314
284
  > 💡 This plugin accepts an optional [configuration object](#configuration).
315
285
 
@@ -319,6 +289,7 @@ const {
319
289
  } = require('@vanilla-extract/next-plugin');
320
290
  const withVanillaExtract = createVanillaExtractPlugin();
321
291
 
292
+ /** @type {import('next').NextConfig} */
322
293
  const nextConfig = {};
323
294
 
324
295
  module.exports = withVanillaExtract(nextConfig);
@@ -336,11 +307,25 @@ const withMDX = require('@next/mdx')({
336
307
  extension: /\.mdx$/
337
308
  });
338
309
 
310
+ /** @type {import('next').NextConfig} */
339
311
  const nextConfig = {};
340
312
 
341
313
  module.exports = withVanillaExtract(withMDX(nextConfig));
342
314
  ```
343
315
 
316
+ 3. (Optional) If you want to automatically generate debug IDs during development, you can add the [Babel](https://babeljs.io) plugin. Note that this step will cause Next.js to switch from [SWC](https://github.com/swc-project/swc) to Babel, increasing build times. This may or may not be an issue depending on the size of your project.
317
+
318
+ > Note: While optional for Next.js, the Babel plugin is still required when trying to run `.css.ts` files in Node for unit testing since the files are no longer being processed by a bundler.
319
+
320
+ If you don't have a `.babelrc` file in the root of your project, create one. Add the Babel plugin to your `.babelrc` file, ensuring that you're also including `"next/babel"` in your `presets` array.
321
+
322
+ ```json
323
+ {
324
+ "presets": ["next/babel"],
325
+ "plugins": ["@vanilla-extract/babel-plugin"]
326
+ }
327
+ ```
328
+
344
329
  ### Gatsby
345
330
 
346
331
  To add to your [Gatsby](https://www.gatsbyjs.com) site, use the [gatsby-plugin-vanilla-extract](https://github.com/KyleAMathews/gatsby-plugin-vanilla-extract) plugin.
@@ -1,12 +1,7 @@
1
- import type { Plugin } from 'vite';
2
- import { IdentifierOption } from '@vanilla-extract/integration';
3
- interface Options {
4
- identifiers?: IdentifierOption;
5
- /**
6
- * Which CSS runtime to use when running `vite serve`.
7
- * @default 'vite'
8
- */
9
- devStyleRuntime?: 'vite' | 'vanilla-extract';
10
- }
11
- export declare function vanillaExtractPlugin({ identifiers, devStyleRuntime, }?: Options): Plugin;
12
- export {};
1
+ import type { Plugin } from 'vite';
2
+ import { IdentifierOption } from '@vanilla-extract/integration';
3
+ interface Options {
4
+ identifiers?: IdentifierOption;
5
+ }
6
+ export declare function vanillaExtractPlugin({ identifiers }?: Options): Plugin;
7
+ export {};
@@ -0,0 +1,7 @@
1
+ import type { ResolvedConfig } from 'vite';
2
+ import type { ProcessOptions, Plugin } from 'postcss';
3
+ export interface PostCSSConfigResult {
4
+ options: ProcessOptions;
5
+ plugins: Plugin[];
6
+ }
7
+ export declare const resolvePostcssConfig: (config: ResolvedConfig) => Promise<PostCSSConfigResult | null>;
@@ -9,25 +9,83 @@ var integration = require('@vanilla-extract/integration');
9
9
 
10
10
  function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
11
11
 
12
+ function _interopNamespace(e) {
13
+ if (e && e.__esModule) return e;
14
+ var n = Object.create(null);
15
+ if (e) {
16
+ Object.keys(e).forEach(function (k) {
17
+ if (k !== 'default') {
18
+ var d = Object.getOwnPropertyDescriptor(e, k);
19
+ Object.defineProperty(n, k, d.get ? d : {
20
+ enumerable: true,
21
+ get: function () { return e[k]; }
22
+ });
23
+ }
24
+ });
25
+ }
26
+ n["default"] = e;
27
+ return Object.freeze(n);
28
+ }
29
+
12
30
  var path__default = /*#__PURE__*/_interopDefault(path);
13
31
  var outdent__default = /*#__PURE__*/_interopDefault(outdent);
14
32
 
33
+ // Mostly copied from vite's implementation
34
+ // https://github.com/vitejs/vite/blob/efec70f816b80e55b64255b32a5f120e1cf4e4be/packages/vite/src/node/plugins/css.ts
35
+ const resolvePostcssConfig = async config => {
36
+ // inline postcss config via vite config
37
+ const inlineOptions = config.css?.postcss;
38
+ const inlineOptionsIsString = typeof inlineOptions === 'string';
39
+
40
+ if (inlineOptions && !inlineOptionsIsString) {
41
+ const options = { ...inlineOptions
42
+ };
43
+ delete options.plugins;
44
+ return {
45
+ options,
46
+ plugins: inlineOptions.plugins || []
47
+ };
48
+ } else {
49
+ try {
50
+ const searchPath = typeof inlineOptions === 'string' ? inlineOptions : config.root;
51
+ const postCssConfig = await (await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('postcss-load-config')); })).default({}, searchPath);
52
+ return {
53
+ options: postCssConfig.options,
54
+ // @ts-expect-error - The postcssrc options don't agree with real postcss, but it should be ok
55
+ plugins: postCssConfig.plugins
56
+ };
57
+ } catch (e) {
58
+ if (!/No PostCSS Config found/.test(e.message)) {
59
+ throw e;
60
+ }
61
+
62
+ return null;
63
+ }
64
+ }
65
+ };
66
+
67
+ const styleUpdateEvent = fileId => `vanilla-extract-style-update:${fileId}`;
68
+
69
+ const virtualPrefix = 'virtual:vanilla-extract:';
15
70
  function vanillaExtractPlugin({
16
- identifiers,
17
- devStyleRuntime = 'vite'
71
+ identifiers
18
72
  } = {}) {
19
73
  let config;
20
74
  let packageInfo;
21
- let useRuntime = false;
75
+ let server;
76
+ let postCssConfig;
22
77
  const cssMap = new Map();
23
78
  let virtualExt;
24
79
  return {
25
80
  name: 'vanilla-extract',
26
81
  enforce: 'pre',
27
82
 
83
+ configureServer(_server) {
84
+ server = _server;
85
+ },
86
+
28
87
  config(_userConfig, env) {
29
- useRuntime = devStyleRuntime === 'vanilla-extract' && env.command === 'serve';
30
- const include = useRuntime ? ['@vanilla-extract/css/injectStyles'] : [];
88
+ const include = env.command === 'serve' ? ['@vanilla-extract/css/injectStyles'] : [];
31
89
  return {
32
90
  optimizeDeps: {
33
91
  include
@@ -38,23 +96,26 @@ function vanillaExtractPlugin({
38
96
  };
39
97
  },
40
98
 
41
- configResolved(resolvedConfig) {
99
+ async configResolved(resolvedConfig) {
42
100
  config = resolvedConfig;
43
- virtualExt = `.vanilla.${useRuntime ? 'js' : 'css'}?hash=`;
101
+
102
+ if (config.command === 'serve') {
103
+ postCssConfig = await resolvePostcssConfig(config);
104
+ }
105
+
106
+ virtualExt = `.vanilla.${config.command === 'serve' ? 'js' : 'css'}`;
44
107
  packageInfo = integration.getPackageInfo(config.root);
45
108
  },
46
109
 
47
110
  resolveId(id) {
48
- if (id.indexOf(virtualExt) > 0) {
111
+ if (id.indexOf(virtualPrefix) === 0) {
49
112
  return id;
50
113
  }
51
114
  },
52
115
 
53
116
  load(id) {
54
- const extensionIndex = id.indexOf(virtualExt);
55
-
56
- if (extensionIndex > 0) {
57
- const fileScopeId = id.substring(0, extensionIndex);
117
+ if (id.indexOf(virtualPrefix) === 0) {
118
+ const fileScopeId = id.slice(virtualPrefix.length, id.indexOf(virtualExt));
58
119
 
59
120
  if (!cssMap.has(fileScopeId)) {
60
121
  throw new Error(`Unable to locate ${fileScopeId} in the CSS map.`);
@@ -62,36 +123,50 @@ function vanillaExtractPlugin({
62
123
 
63
124
  const css = cssMap.get(fileScopeId);
64
125
 
65
- if (!useRuntime) {
126
+ if (!server) {
66
127
  return css;
67
128
  }
68
129
 
69
130
  const fileScope = integration.parseFileScope(fileScopeId);
70
- return outdent__default['default']`
131
+ return outdent__default["default"]`
71
132
  import { injectStyles } from '@vanilla-extract/css/injectStyles';
72
133
 
73
- injectStyles({
134
+ const inject = (css) => injectStyles({
74
135
  fileScope: ${JSON.stringify(fileScope)},
75
- css: ${JSON.stringify(css)}
76
- })
136
+ css
137
+ });
138
+
139
+ inject(${JSON.stringify(css)});
140
+
141
+ import.meta.hot.on('${styleUpdateEvent(fileScopeId)}', (css) => {
142
+ inject(css);
143
+ });
77
144
  `;
78
145
  }
79
146
 
80
147
  return null;
81
148
  },
82
149
 
83
- async transform(code, id, ssr) {
150
+ async transform(code, id, ssrParam) {
84
151
  if (!integration.cssFileFilter.test(id)) {
85
152
  return null;
86
153
  }
87
154
 
155
+ let ssr;
156
+
157
+ if (typeof ssrParam === 'boolean') {
158
+ ssr = ssrParam;
159
+ } else {
160
+ ssr = ssrParam?.ssr;
161
+ }
162
+
88
163
  const index = id.indexOf('?');
89
164
  const validId = index === -1 ? id : id.substring(0, index);
90
165
 
91
166
  if (ssr) {
92
167
  return integration.addFileScope({
93
168
  source: code,
94
- filePath: vite.normalizePath(path__default['default'].relative(packageInfo.dirname, validId)),
169
+ filePath: vite.normalizePath(path__default["default"].relative(packageInfo.dirname, validId)),
95
170
  packageInfo
96
171
  }).source;
97
172
  }
@@ -115,14 +190,42 @@ function vanillaExtractPlugin({
115
190
  return integration.processVanillaFile({
116
191
  source,
117
192
  filePath: validId,
118
- identOption: identifiers !== null && identifiers !== void 0 ? identifiers : config.mode === 'production' ? 'short' : 'debug',
119
- serializeVirtualCssPath: ({
193
+ identOption: identifiers ?? (config.mode === 'production' ? 'short' : 'debug'),
194
+ serializeVirtualCssPath: async ({
120
195
  fileScope,
121
196
  source
122
197
  }) => {
123
198
  const fileId = integration.stringifyFileScope(fileScope);
124
- cssMap.set(fileId, source);
125
- return `import "${fileId}${virtualExt}${integration.hash(source)}";`;
199
+ const id = `${virtualPrefix}${fileId}${virtualExt}`;
200
+ let cssSource = source;
201
+
202
+ if (postCssConfig) {
203
+ const postCssResult = await (await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('postcss')); })).default(postCssConfig.plugins).process(source, { ...postCssConfig.options,
204
+ from: undefined,
205
+ map: false
206
+ });
207
+ cssSource = postCssResult.css;
208
+ }
209
+
210
+ if (server && cssMap.has(fileId) && cssMap.get(fileId) !== source) {
211
+ const {
212
+ moduleGraph
213
+ } = server;
214
+ const module = moduleGraph.getModuleById(id);
215
+
216
+ if (module) {
217
+ moduleGraph.invalidateModule(module);
218
+ }
219
+
220
+ server.ws.send({
221
+ type: 'custom',
222
+ event: styleUpdateEvent(fileId),
223
+ data: cssSource
224
+ });
225
+ }
226
+
227
+ cssMap.set(fileId, cssSource);
228
+ return `import "${id}";`;
126
229
  }
127
230
  });
128
231
  }
@@ -9,25 +9,83 @@ var integration = require('@vanilla-extract/integration');
9
9
 
10
10
  function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
11
11
 
12
+ function _interopNamespace(e) {
13
+ if (e && e.__esModule) return e;
14
+ var n = Object.create(null);
15
+ if (e) {
16
+ Object.keys(e).forEach(function (k) {
17
+ if (k !== 'default') {
18
+ var d = Object.getOwnPropertyDescriptor(e, k);
19
+ Object.defineProperty(n, k, d.get ? d : {
20
+ enumerable: true,
21
+ get: function () { return e[k]; }
22
+ });
23
+ }
24
+ });
25
+ }
26
+ n["default"] = e;
27
+ return Object.freeze(n);
28
+ }
29
+
12
30
  var path__default = /*#__PURE__*/_interopDefault(path);
13
31
  var outdent__default = /*#__PURE__*/_interopDefault(outdent);
14
32
 
33
+ // Mostly copied from vite's implementation
34
+ // https://github.com/vitejs/vite/blob/efec70f816b80e55b64255b32a5f120e1cf4e4be/packages/vite/src/node/plugins/css.ts
35
+ const resolvePostcssConfig = async config => {
36
+ // inline postcss config via vite config
37
+ const inlineOptions = config.css?.postcss;
38
+ const inlineOptionsIsString = typeof inlineOptions === 'string';
39
+
40
+ if (inlineOptions && !inlineOptionsIsString) {
41
+ const options = { ...inlineOptions
42
+ };
43
+ delete options.plugins;
44
+ return {
45
+ options,
46
+ plugins: inlineOptions.plugins || []
47
+ };
48
+ } else {
49
+ try {
50
+ const searchPath = typeof inlineOptions === 'string' ? inlineOptions : config.root;
51
+ const postCssConfig = await (await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('postcss-load-config')); })).default({}, searchPath);
52
+ return {
53
+ options: postCssConfig.options,
54
+ // @ts-expect-error - The postcssrc options don't agree with real postcss, but it should be ok
55
+ plugins: postCssConfig.plugins
56
+ };
57
+ } catch (e) {
58
+ if (!/No PostCSS Config found/.test(e.message)) {
59
+ throw e;
60
+ }
61
+
62
+ return null;
63
+ }
64
+ }
65
+ };
66
+
67
+ const styleUpdateEvent = fileId => `vanilla-extract-style-update:${fileId}`;
68
+
69
+ const virtualPrefix = 'virtual:vanilla-extract:';
15
70
  function vanillaExtractPlugin({
16
- identifiers,
17
- devStyleRuntime = 'vite'
71
+ identifiers
18
72
  } = {}) {
19
73
  let config;
20
74
  let packageInfo;
21
- let useRuntime = false;
75
+ let server;
76
+ let postCssConfig;
22
77
  const cssMap = new Map();
23
78
  let virtualExt;
24
79
  return {
25
80
  name: 'vanilla-extract',
26
81
  enforce: 'pre',
27
82
 
83
+ configureServer(_server) {
84
+ server = _server;
85
+ },
86
+
28
87
  config(_userConfig, env) {
29
- useRuntime = devStyleRuntime === 'vanilla-extract' && env.command === 'serve';
30
- const include = useRuntime ? ['@vanilla-extract/css/injectStyles'] : [];
88
+ const include = env.command === 'serve' ? ['@vanilla-extract/css/injectStyles'] : [];
31
89
  return {
32
90
  optimizeDeps: {
33
91
  include
@@ -38,23 +96,26 @@ function vanillaExtractPlugin({
38
96
  };
39
97
  },
40
98
 
41
- configResolved(resolvedConfig) {
99
+ async configResolved(resolvedConfig) {
42
100
  config = resolvedConfig;
43
- virtualExt = `.vanilla.${useRuntime ? 'js' : 'css'}?hash=`;
101
+
102
+ if (config.command === 'serve') {
103
+ postCssConfig = await resolvePostcssConfig(config);
104
+ }
105
+
106
+ virtualExt = `.vanilla.${config.command === 'serve' ? 'js' : 'css'}`;
44
107
  packageInfo = integration.getPackageInfo(config.root);
45
108
  },
46
109
 
47
110
  resolveId(id) {
48
- if (id.indexOf(virtualExt) > 0) {
111
+ if (id.indexOf(virtualPrefix) === 0) {
49
112
  return id;
50
113
  }
51
114
  },
52
115
 
53
116
  load(id) {
54
- const extensionIndex = id.indexOf(virtualExt);
55
-
56
- if (extensionIndex > 0) {
57
- const fileScopeId = id.substring(0, extensionIndex);
117
+ if (id.indexOf(virtualPrefix) === 0) {
118
+ const fileScopeId = id.slice(virtualPrefix.length, id.indexOf(virtualExt));
58
119
 
59
120
  if (!cssMap.has(fileScopeId)) {
60
121
  throw new Error(`Unable to locate ${fileScopeId} in the CSS map.`);
@@ -62,36 +123,50 @@ function vanillaExtractPlugin({
62
123
 
63
124
  const css = cssMap.get(fileScopeId);
64
125
 
65
- if (!useRuntime) {
126
+ if (!server) {
66
127
  return css;
67
128
  }
68
129
 
69
130
  const fileScope = integration.parseFileScope(fileScopeId);
70
- return outdent__default['default']`
131
+ return outdent__default["default"]`
71
132
  import { injectStyles } from '@vanilla-extract/css/injectStyles';
72
133
 
73
- injectStyles({
134
+ const inject = (css) => injectStyles({
74
135
  fileScope: ${JSON.stringify(fileScope)},
75
- css: ${JSON.stringify(css)}
76
- })
136
+ css
137
+ });
138
+
139
+ inject(${JSON.stringify(css)});
140
+
141
+ import.meta.hot.on('${styleUpdateEvent(fileScopeId)}', (css) => {
142
+ inject(css);
143
+ });
77
144
  `;
78
145
  }
79
146
 
80
147
  return null;
81
148
  },
82
149
 
83
- async transform(code, id, ssr) {
150
+ async transform(code, id, ssrParam) {
84
151
  if (!integration.cssFileFilter.test(id)) {
85
152
  return null;
86
153
  }
87
154
 
155
+ let ssr;
156
+
157
+ if (typeof ssrParam === 'boolean') {
158
+ ssr = ssrParam;
159
+ } else {
160
+ ssr = ssrParam?.ssr;
161
+ }
162
+
88
163
  const index = id.indexOf('?');
89
164
  const validId = index === -1 ? id : id.substring(0, index);
90
165
 
91
166
  if (ssr) {
92
167
  return integration.addFileScope({
93
168
  source: code,
94
- filePath: vite.normalizePath(path__default['default'].relative(packageInfo.dirname, validId)),
169
+ filePath: vite.normalizePath(path__default["default"].relative(packageInfo.dirname, validId)),
95
170
  packageInfo
96
171
  }).source;
97
172
  }
@@ -115,14 +190,42 @@ function vanillaExtractPlugin({
115
190
  return integration.processVanillaFile({
116
191
  source,
117
192
  filePath: validId,
118
- identOption: identifiers !== null && identifiers !== void 0 ? identifiers : config.mode === 'production' ? 'short' : 'debug',
119
- serializeVirtualCssPath: ({
193
+ identOption: identifiers ?? (config.mode === 'production' ? 'short' : 'debug'),
194
+ serializeVirtualCssPath: async ({
120
195
  fileScope,
121
196
  source
122
197
  }) => {
123
198
  const fileId = integration.stringifyFileScope(fileScope);
124
- cssMap.set(fileId, source);
125
- return `import "${fileId}${virtualExt}${integration.hash(source)}";`;
199
+ const id = `${virtualPrefix}${fileId}${virtualExt}`;
200
+ let cssSource = source;
201
+
202
+ if (postCssConfig) {
203
+ const postCssResult = await (await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('postcss')); })).default(postCssConfig.plugins).process(source, { ...postCssConfig.options,
204
+ from: undefined,
205
+ map: false
206
+ });
207
+ cssSource = postCssResult.css;
208
+ }
209
+
210
+ if (server && cssMap.has(fileId) && cssMap.get(fileId) !== source) {
211
+ const {
212
+ moduleGraph
213
+ } = server;
214
+ const module = moduleGraph.getModuleById(id);
215
+
216
+ if (module) {
217
+ moduleGraph.invalidateModule(module);
218
+ }
219
+
220
+ server.ws.send({
221
+ type: 'custom',
222
+ event: styleUpdateEvent(fileId),
223
+ data: cssSource
224
+ });
225
+ }
226
+
227
+ cssMap.set(fileId, cssSource);
228
+ return `import "${id}";`;
126
229
  }
127
230
  });
128
231
  }
@@ -1,24 +1,64 @@
1
1
  import path from 'path';
2
2
  import { normalizePath } from 'vite';
3
3
  import outdent from 'outdent';
4
- import { getPackageInfo, parseFileScope, cssFileFilter, addFileScope, compile, processVanillaFile, stringifyFileScope, hash } from '@vanilla-extract/integration';
4
+ import { getPackageInfo, parseFileScope, cssFileFilter, addFileScope, compile, processVanillaFile, stringifyFileScope } from '@vanilla-extract/integration';
5
+
6
+ // Mostly copied from vite's implementation
7
+ // https://github.com/vitejs/vite/blob/efec70f816b80e55b64255b32a5f120e1cf4e4be/packages/vite/src/node/plugins/css.ts
8
+ const resolvePostcssConfig = async config => {
9
+ // inline postcss config via vite config
10
+ const inlineOptions = config.css?.postcss;
11
+ const inlineOptionsIsString = typeof inlineOptions === 'string';
12
+
13
+ if (inlineOptions && !inlineOptionsIsString) {
14
+ const options = { ...inlineOptions
15
+ };
16
+ delete options.plugins;
17
+ return {
18
+ options,
19
+ plugins: inlineOptions.plugins || []
20
+ };
21
+ } else {
22
+ try {
23
+ const searchPath = typeof inlineOptions === 'string' ? inlineOptions : config.root;
24
+ const postCssConfig = await (await import('postcss-load-config')).default({}, searchPath);
25
+ return {
26
+ options: postCssConfig.options,
27
+ // @ts-expect-error - The postcssrc options don't agree with real postcss, but it should be ok
28
+ plugins: postCssConfig.plugins
29
+ };
30
+ } catch (e) {
31
+ if (!/No PostCSS Config found/.test(e.message)) {
32
+ throw e;
33
+ }
5
34
 
35
+ return null;
36
+ }
37
+ }
38
+ };
39
+
40
+ const styleUpdateEvent = fileId => `vanilla-extract-style-update:${fileId}`;
41
+
42
+ const virtualPrefix = 'virtual:vanilla-extract:';
6
43
  function vanillaExtractPlugin({
7
- identifiers,
8
- devStyleRuntime = 'vite'
44
+ identifiers
9
45
  } = {}) {
10
46
  let config;
11
47
  let packageInfo;
12
- let useRuntime = false;
48
+ let server;
49
+ let postCssConfig;
13
50
  const cssMap = new Map();
14
51
  let virtualExt;
15
52
  return {
16
53
  name: 'vanilla-extract',
17
54
  enforce: 'pre',
18
55
 
56
+ configureServer(_server) {
57
+ server = _server;
58
+ },
59
+
19
60
  config(_userConfig, env) {
20
- useRuntime = devStyleRuntime === 'vanilla-extract' && env.command === 'serve';
21
- const include = useRuntime ? ['@vanilla-extract/css/injectStyles'] : [];
61
+ const include = env.command === 'serve' ? ['@vanilla-extract/css/injectStyles'] : [];
22
62
  return {
23
63
  optimizeDeps: {
24
64
  include
@@ -29,23 +69,26 @@ function vanillaExtractPlugin({
29
69
  };
30
70
  },
31
71
 
32
- configResolved(resolvedConfig) {
72
+ async configResolved(resolvedConfig) {
33
73
  config = resolvedConfig;
34
- virtualExt = `.vanilla.${useRuntime ? 'js' : 'css'}?hash=`;
74
+
75
+ if (config.command === 'serve') {
76
+ postCssConfig = await resolvePostcssConfig(config);
77
+ }
78
+
79
+ virtualExt = `.vanilla.${config.command === 'serve' ? 'js' : 'css'}`;
35
80
  packageInfo = getPackageInfo(config.root);
36
81
  },
37
82
 
38
83
  resolveId(id) {
39
- if (id.indexOf(virtualExt) > 0) {
84
+ if (id.indexOf(virtualPrefix) === 0) {
40
85
  return id;
41
86
  }
42
87
  },
43
88
 
44
89
  load(id) {
45
- const extensionIndex = id.indexOf(virtualExt);
46
-
47
- if (extensionIndex > 0) {
48
- const fileScopeId = id.substring(0, extensionIndex);
90
+ if (id.indexOf(virtualPrefix) === 0) {
91
+ const fileScopeId = id.slice(virtualPrefix.length, id.indexOf(virtualExt));
49
92
 
50
93
  if (!cssMap.has(fileScopeId)) {
51
94
  throw new Error(`Unable to locate ${fileScopeId} in the CSS map.`);
@@ -53,7 +96,7 @@ function vanillaExtractPlugin({
53
96
 
54
97
  const css = cssMap.get(fileScopeId);
55
98
 
56
- if (!useRuntime) {
99
+ if (!server) {
57
100
  return css;
58
101
  }
59
102
 
@@ -61,21 +104,35 @@ function vanillaExtractPlugin({
61
104
  return outdent`
62
105
  import { injectStyles } from '@vanilla-extract/css/injectStyles';
63
106
 
64
- injectStyles({
107
+ const inject = (css) => injectStyles({
65
108
  fileScope: ${JSON.stringify(fileScope)},
66
- css: ${JSON.stringify(css)}
67
- })
109
+ css
110
+ });
111
+
112
+ inject(${JSON.stringify(css)});
113
+
114
+ import.meta.hot.on('${styleUpdateEvent(fileScopeId)}', (css) => {
115
+ inject(css);
116
+ });
68
117
  `;
69
118
  }
70
119
 
71
120
  return null;
72
121
  },
73
122
 
74
- async transform(code, id, ssr) {
123
+ async transform(code, id, ssrParam) {
75
124
  if (!cssFileFilter.test(id)) {
76
125
  return null;
77
126
  }
78
127
 
128
+ let ssr;
129
+
130
+ if (typeof ssrParam === 'boolean') {
131
+ ssr = ssrParam;
132
+ } else {
133
+ ssr = ssrParam?.ssr;
134
+ }
135
+
79
136
  const index = id.indexOf('?');
80
137
  const validId = index === -1 ? id : id.substring(0, index);
81
138
 
@@ -106,14 +163,42 @@ function vanillaExtractPlugin({
106
163
  return processVanillaFile({
107
164
  source,
108
165
  filePath: validId,
109
- identOption: identifiers !== null && identifiers !== void 0 ? identifiers : config.mode === 'production' ? 'short' : 'debug',
110
- serializeVirtualCssPath: ({
166
+ identOption: identifiers ?? (config.mode === 'production' ? 'short' : 'debug'),
167
+ serializeVirtualCssPath: async ({
111
168
  fileScope,
112
169
  source
113
170
  }) => {
114
171
  const fileId = stringifyFileScope(fileScope);
115
- cssMap.set(fileId, source);
116
- return `import "${fileId}${virtualExt}${hash(source)}";`;
172
+ const id = `${virtualPrefix}${fileId}${virtualExt}`;
173
+ let cssSource = source;
174
+
175
+ if (postCssConfig) {
176
+ const postCssResult = await (await import('postcss')).default(postCssConfig.plugins).process(source, { ...postCssConfig.options,
177
+ from: undefined,
178
+ map: false
179
+ });
180
+ cssSource = postCssResult.css;
181
+ }
182
+
183
+ if (server && cssMap.has(fileId) && cssMap.get(fileId) !== source) {
184
+ const {
185
+ moduleGraph
186
+ } = server;
187
+ const module = moduleGraph.getModuleById(id);
188
+
189
+ if (module) {
190
+ moduleGraph.invalidateModule(module);
191
+ }
192
+
193
+ server.ws.send({
194
+ type: 'custom',
195
+ event: styleUpdateEvent(fileId),
196
+ data: cssSource
197
+ });
198
+ }
199
+
200
+ cssMap.set(fileId, cssSource);
201
+ return `import "${id}";`;
117
202
  }
118
203
  });
119
204
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vanilla-extract/vite-plugin",
3
- "version": "2.1.3",
3
+ "version": "3.1.1",
4
4
  "description": "Zero-runtime Stylesheets-in-TypeScript",
5
5
  "main": "dist/vanilla-extract-vite-plugin.cjs.js",
6
6
  "module": "dist/vanilla-extract-vite-plugin.esm.js",
@@ -15,13 +15,15 @@
15
15
  "author": "SEEK",
16
16
  "license": "MIT",
17
17
  "dependencies": {
18
- "@vanilla-extract/integration": "^1.4.3",
19
- "outdent": "^0.8.0"
18
+ "@vanilla-extract/integration": "^2.0.0",
19
+ "outdent": "^0.8.0",
20
+ "postcss": "^8.3.6",
21
+ "postcss-load-config": "^3.1.0"
20
22
  },
21
23
  "devDependencies": {
22
- "vite": "^2.6.0"
24
+ "vite": "^2.7.0"
23
25
  },
24
26
  "peerDependencies": {
25
27
  "vite": "^2.2.3"
26
28
  }
27
- }
29
+ }
package/CHANGELOG.md DELETED
@@ -1,173 +0,0 @@
1
- # @vanilla-extract/vite-plugin
2
-
3
- ## 2.1.3
4
-
5
- ### Patch Changes
6
-
7
- - [#409](https://github.com/seek-oss/vanilla-extract/pull/409) [`a9c5cb7`](https://github.com/seek-oss/vanilla-extract/commit/a9c5cb768ad10bd25dd1a31041733fc96cd467a0) Thanks [@benjervis](https://github.com/benjervis)! - Fix plugin for watch mode.
8
-
9
- The vite plugin previously relied on a one to one matching of resolve to load calls, and would clean up the CSS stored in memory after it was loaded.
10
-
11
- This isn't true in `--watch` mode, as the same file can be loaded on the rebuild without having to be resolved, which the plugin now handles.
12
-
13
- * [#409](https://github.com/seek-oss/vanilla-extract/pull/409) [`a9c5cb7`](https://github.com/seek-oss/vanilla-extract/commit/a9c5cb768ad10bd25dd1a31041733fc96cd467a0) Thanks [@benjervis](https://github.com/benjervis)! - Update the "vanilla-extract" devStyleRuntime option.
14
-
15
- When using the vanilla browser runtime in vite, it now operates on a new model where a .css.js file is generated, that uses @vanilla-extract/css/injectStyles to add the css to the browser.
16
-
17
- This allows for hot reloading of styles, and makes styles a bit easier to debug at dev time (because they're actually visible).
18
-
19
- - [#409](https://github.com/seek-oss/vanilla-extract/pull/409) [`a9c5cb7`](https://github.com/seek-oss/vanilla-extract/commit/a9c5cb768ad10bd25dd1a31041733fc96cd467a0) Thanks [@benjervis](https://github.com/benjervis)! - Handle vite 2.6.
20
-
21
- As of vite 2.6 and greater, `?used` gets appended to css imports, which causes the file imports to be not what we expected.
22
-
23
- This caused mismatching classnames in the vite plugin, and it caused the babel plugin to not add filescopes when it should have.
24
-
25
- * [#409](https://github.com/seek-oss/vanilla-extract/pull/409) [`a9c5cb7`](https://github.com/seek-oss/vanilla-extract/commit/a9c5cb768ad10bd25dd1a31041733fc96cd467a0) Thanks [@benjervis](https://github.com/benjervis)! - Automatically optimize deps.
26
-
27
- When using the new vanilla browser runtime, the new `injectStyles` dependency gets injected at runtime, so vite can't discover it ahead of time and pre-bundle it.
28
-
29
- The plugin will now add the dependency to optimizeDeps if the vanilla runtime is being used so that it's optimized up front.
30
- It also ensures that some relevant vanilla packages are externalised in SSR mode.
31
-
32
- * Updated dependencies [[`a9c5cb7`](https://github.com/seek-oss/vanilla-extract/commit/a9c5cb768ad10bd25dd1a31041733fc96cd467a0)]:
33
- - @vanilla-extract/integration@1.4.3
34
-
35
- ## 2.1.2
36
-
37
- ### Patch Changes
38
-
39
- - [#398](https://github.com/seek-oss/vanilla-extract/pull/398) [`63f4ed0`](https://github.com/seek-oss/vanilla-extract/commit/63f4ed0e67419df565f3f447cf27cec612afbb8d) Thanks [@benjervis](https://github.com/benjervis)! - Fixes a bug with vite where "?used" is appended to the file path of css files.
40
-
41
- This could cause different class name hashes to be generated between SSR and client builds.
42
- This was introduced in vite 2.6.0.
43
-
44
- ## 2.1.1
45
-
46
- ### Patch Changes
47
-
48
- - [#393](https://github.com/seek-oss/vanilla-extract/pull/393) [`2f379f1`](https://github.com/seek-oss/vanilla-extract/commit/2f379f118c2a2fe6dc08a1cc15a395dbc0f17ece) Thanks [@mattcompiles](https://github.com/mattcompiles)! - Fix compilation errors in Vite 2.6
49
-
50
- - Updated dependencies [[`2f379f1`](https://github.com/seek-oss/vanilla-extract/commit/2f379f118c2a2fe6dc08a1cc15a395dbc0f17ece)]:
51
- - @vanilla-extract/integration@1.4.2
52
-
53
- ## 2.1.0
54
-
55
- ### Minor Changes
56
-
57
- - [#373](https://github.com/seek-oss/vanilla-extract/pull/373) [`a55d2cf`](https://github.com/seek-oss/vanilla-extract/commit/a55d2cfd7c4ca9175a2c86557888df90907bfd0f) Thanks [@mattcompiles](https://github.com/mattcompiles)! - Add `devStyleRuntime` option to allow switching between dev style runtimes
58
-
59
- The built-in Vite dev style runtime (what adds styles to the page when running `vite serve`) doesn't seem to clean up old styles as expected. Passing `devStyleRuntime: 'vanilla-extract'` will instead use vanilla-extract's browser runtime. This pushes all style creation in development to the browser, but may give a better HMR experience.
60
-
61
- ## 2.0.2
62
-
63
- ### Patch Changes
64
-
65
- - [#341](https://github.com/seek-oss/vanilla-extract/pull/341) [`0b743e7`](https://github.com/seek-oss/vanilla-extract/commit/0b743e744447616f8daf0c6b88beff8ffef8d41b) Thanks [@mattcompiles](https://github.com/mattcompiles)! - Refactor SSR file scoping to use centralised `addFileScope` implementation
66
-
67
- - Updated dependencies [[`50bae14`](https://github.com/seek-oss/vanilla-extract/commit/50bae14bf38c8a971ad1727cb8e827c86da06772), [`0b743e7`](https://github.com/seek-oss/vanilla-extract/commit/0b743e744447616f8daf0c6b88beff8ffef8d41b)]:
68
- - @vanilla-extract/integration@1.3.0
69
-
70
- ## 2.0.1
71
-
72
- ### Patch Changes
73
-
74
- - [#327](https://github.com/seek-oss/vanilla-extract/pull/327) [`73b55f8`](https://github.com/seek-oss/vanilla-extract/commit/73b55f8e7e205701abdb1cbb029c3f2f5080b6fd) Thanks [@benjervis](https://github.com/benjervis)! - Fix bug where precompiled .css.ts files (.css.js) were treated differently in SSR mode.
75
-
76
- ## 2.0.0
77
-
78
- ### Major Changes
79
-
80
- - [#323](https://github.com/seek-oss/vanilla-extract/pull/323) [`1e7d647`](https://github.com/seek-oss/vanilla-extract/commit/1e7d6470398a0fbcbdef4118e678150932cd9275) Thanks [@mattcompiles](https://github.com/mattcompiles)! - Formatting of identifiers (e.g. class names, keyframes, CSS Vars, etc) can now be configured via the `identifiers` option which accepts either `short` or `debug`.
81
-
82
- - `short` identifiers are a 7+ character hash. e.g. `hnw5tz3`
83
- - `debug` identifiers contain human readable prefixes representing the owning filename and a potential rule level debug name. e.g. `somefile_mystyle_hnw5tz3`
84
-
85
- ```js
86
- import { vanillaExtractPlugin } from '@vanilla-extract/vite-plugin';
87
-
88
- vanillaExtractPlugin({ identifiers: 'short' });
89
- ```
90
-
91
- BREAKING CHANGE
92
-
93
- Previously identifiers were formatted as `short` when `process.env.NODE_ENV` was set to "production". By default, they will now be formatted according to Vite's [mode config](https://vitejs.dev/config/#mode).
94
-
95
- ### Patch Changes
96
-
97
- - Updated dependencies [[`1e7d647`](https://github.com/seek-oss/vanilla-extract/commit/1e7d6470398a0fbcbdef4118e678150932cd9275)]:
98
- - @vanilla-extract/integration@1.2.0
99
-
100
- ## 1.2.0
101
-
102
- ### Minor Changes
103
-
104
- - [#311](https://github.com/seek-oss/vanilla-extract/pull/311) [`416eb9a`](https://github.com/seek-oss/vanilla-extract/commit/416eb9ae99661597a8443594f4376aacf4d295cc) Thanks [@mattcompiles](https://github.com/mattcompiles)! - In SSR mode, move to runtime evaluation of vanilla-extract files
105
-
106
- This unlocks the potential for CSS extraction on the server.
107
-
108
- ## 1.1.2
109
-
110
- ### Patch Changes
111
-
112
- - [#290](https://github.com/seek-oss/vanilla-extract/pull/290) [`adc1d64`](https://github.com/seek-oss/vanilla-extract/commit/adc1d644635a1197edd36f522f78658a641027d4) Thanks [@ygj6](https://github.com/ygj6)! - Normalize path of generated CSS files
113
-
114
- ## 1.1.1
115
-
116
- ### Patch Changes
117
-
118
- - [#270](https://github.com/seek-oss/vanilla-extract/pull/270) [`fe19158`](https://github.com/seek-oss/vanilla-extract/commit/fe1915808b374a1bbf8f67eca85c0253153e2cb9) Thanks [@yyx990803](https://github.com/yyx990803)! - Fix watching of modules imported by `.css.ts` files
119
-
120
- ## 1.1.0
121
-
122
- ### Minor Changes
123
-
124
- - [#259](https://github.com/seek-oss/vanilla-extract/pull/259) [`b8a6441`](https://github.com/seek-oss/vanilla-extract/commit/b8a6441e3400be388a520e3acf94f3bb6519cf0a) Thanks [@markdalgleish](https://github.com/markdalgleish)! - Allow the result of `composeStyles` to be used in selectors
125
-
126
- When style compositions are used in selectors, they are now assigned an additional class so they can be uniquely identified. When selectors are processed internally, the composed classes are removed, only leaving behind the unique identifier classes. This allows you to treat them as if they were a single class within vanilla-extract selectors.
127
-
128
- ```ts
129
- import { style, globalStyle, composeStyles } from '@vanilla-extract/css';
130
-
131
- const background = style({ background: 'mintcream' });
132
- const padding = style({ padding: 12 });
133
-
134
- export const container = composeStyles(background, padding);
135
-
136
- globalStyle(`${container} *`, {
137
- boxSizing: 'border-box',
138
- });
139
- ```
140
-
141
- ### Patch Changes
142
-
143
- - Updated dependencies [[`b8a6441`](https://github.com/seek-oss/vanilla-extract/commit/b8a6441e3400be388a520e3acf94f3bb6519cf0a)]:
144
- - @vanilla-extract/integration@1.1.0
145
-
146
- ## 1.0.0
147
-
148
- ### Major Changes
149
-
150
- - [#171](https://github.com/seek-oss/vanilla-extract/pull/171) [`84a8611`](https://github.com/seek-oss/vanilla-extract/commit/84a8611972f32a00a6cbd85267a01dd2d31be869) Thanks [@mattcompiles](https://github.com/mattcompiles)! - Release v1
151
-
152
- ### Patch Changes
153
-
154
- - Updated dependencies [[`84a8611`](https://github.com/seek-oss/vanilla-extract/commit/84a8611972f32a00a6cbd85267a01dd2d31be869)]:
155
- - @vanilla-extract/integration@1.0.0
156
-
157
- ## 0.1.1
158
-
159
- ### Patch Changes
160
-
161
- - [#96](https://github.com/seek-oss/vanilla-extract/pull/96) [`697a233`](https://github.com/seek-oss/vanilla-extract/commit/697a2332cdb34886af26224c13f1efb73b6d36b3) Thanks [@mattcompiles](https://github.com/mattcompiles)! - Change vite-plugin to be a named export
162
-
163
- BREAKING CHANGE
164
-
165
- ```diff
166
- -import vanillaExtractPlugin from '@vanilla-extract/vite-plugin';
167
- +import { vanillaExtractPlugin } from '@vanilla-extract/vite-plugin';
168
-
169
- // vite.config.js
170
- export default {
171
- plugins: [vanillaExtractPlugin()]
172
- }
173
- ```