vanilla-extract-css / vanilla-extract Goto Github PK
View Code? Open in Web Editor NEWZero-runtime Stylesheets-in-TypeScript
Home Page: https://vanilla-extract.style
License: MIT License
Zero-runtime Stylesheets-in-TypeScript
Home Page: https://vanilla-extract.style
License: MIT License
When i try to import MyButton.css.ts into the MyButton.vue component file i get the following error:
I've been following the instructions fo Vite as you can see in my example project:
https://github.com/luckyluggi/vanilla-extract-vite
System:
OS: Windows 10 10.0.19042
CPU: (12) x64 Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
Memory: 4.33 GB / 15.92 GB
Binaries:
Node: 14.15.5 - C:\Program Files\nodejs\node.EXE
npm: 6.14.11 - C:\Program Files\nodejs\npm.CMD
Browsers:
Chrome: 91.0.4472.124
Edge: Spartan (44.19041.1023.0), Chromium (91.0.864.67)
Internet Explorer: 11.0.19041.1
npmPackages:
@vanilla-extract/css: ^1.1.0 => 1.1.0
@vanilla-extract/vite-plugin: ^1.0.0 => 1.0.0
vite: ^2.4.2 => 2.4.2
Am i missing some configuration?
Thanks!
I'm using vanilla-extract with a Vite/React/TS project and I've run into a couple issues while in development.
If you remove a style declaration, it still applies to elements using that class.
Let's say you have a declaration like alignItems: "center"
in your class definition and assign it to a div. If you remove that alignItems
declaration and save, it'll still apply to the div after HMR.
Looking at the styles panel in devtools, it seems to be because class names are not changed between saves- a new style definition for the class is added to the page while the previous one remains. The alignItems
declaration is picked up due to the cascade.
I'm not sure if that is expected, but it does make it a bit harder to iterate on styling while in development.
The second issue is, I think, probably what is documented in the Vite Setup section, but just wanted to verify.
If I update a theme property in one file, it'll update in a dependent .css.ts
file until I set the property back to it's original value.
For example, if I set a theme value brand: 'mediumslateblue'
in theme.css.ts
, and use that in styles.css.ts
everything is dandy. If I change brand
to 'pink'
and save, the HMR works as expected. I can keep changing the value and saving and things work as expected- until I set the value back to the original mediumslateblue
. Refreshing the page seems to "reset" this behavior.
Note: There is no cascade issue as in the previous issue- at least none apparent in devtools.
The combination of the two issues means I'm never quite sure if the browser is showing the right thing so I end up refreshing the page a lot just in case. I'm not sure if both of these issues stem from the same Vite limitation but if so, I'll prob just have to wait to use vanilla-extract with this particular project.
This is sad because I love the overall API. I just can't ask my team to put up with the current dev experience resulting from these two issues (and we can't change Vite at this point). I think if the first issue was cleared up we might be able to go ahead since the second issue only really matters while changing a theme (which shouldn't happen often).
Anyways, thanks for your work on this project - it really is an ideal combination of features.
https://github.com/sandgraham/vanilla-extract-vite-issue
This is a freshly scaffolded Vite/React/TS project with some minimal vanilla-extract setup.
Output of npx envinfo --system --npmPackages @vanilla-extract/css,@vanilla-extract/webpack-plugin,@vanilla-extract/esbuild-plugin,@vanilla-extract/vite-plugin,@vanilla-extract/sprinkles,webpack,esbuild,vite --binaries --browsers
:
System:
OS: macOS 11.3.1
CPU: (16) x64 Intel(R) Core(TM) i9-9980HK CPU @ 2.40GHz
Memory: 1.42 GB / 64.00 GB
Shell: 5.8 - /bin/zsh
Binaries:
Node: 14.16.0 - ~/.nvm/versions/node/v14.16.0/bin/node
Yarn: 1.22.10 - ~/.nvm/versions/node/v14.16.0/bin/yarn
npm: 6.14.11 - ~/.nvm/versions/node/v14.16.0/bin/npm
Browsers:
Chrome: 91.0.4472.77
Chrome Canary: 93.0.4535.0
Firefox Developer Edition: 87.0
Safari: 14.1
Safari Technology Preview: 14.2
npmPackages:
@vanilla-extract/css: ^1.0.0 => 1.0.0
@vanilla-extract/vite-plugin: ^1.0.0 => 1.0.0
vite: ^2.0.5 => 2.3.6
Getting an error with vanilla-extract while creating a global theme from a nested structure
// File: src/design-system/default-theme.css.ts
import { Colors, DesignSystem, Sizing } from '@newrade/core-design-system';
import { createThemeContract } from '@vanilla-extract/css';
import { defaultCSSButtons } from './default-buttons';
import { defaultCSSColors } from './default-colors';
import { defaultCSSSizing } from './default-sizing';
export const colorVars = createThemeContract<Colors<string>>(defaultCSSColors);
export const sizingVars = createThemeContract<Sizing<string>>(defaultCSSSizing);
export const buttonsVars =
createThemeContract<Pick<DesignSystem<string>['components'], 'buttons'>>(defaultCSSButtons);
and then I import those in my app
// File: src/design-system/theme.css.ts
import { DesignSystem } from '@newrade/core-design-system';
import {
buttonsVars,
colorVars,
defaultCSSButtons,
defaultCSSColors,
defaultCSSSizing,
placeholderButtonSize,
placeholderButtonVariant,
sizingVars,
} from '@newrade/core-react-ui';
import { createGlobalTheme, createTheme, globalStyle } from '@vanilla-extract/css';
globalStyle('html, body', {
margin: 0,
padding: 0,
});
// @ts-expect-error
createGlobalTheme(':root', sizingVars, defaultCSSSizing);
// @ts-expect-error
createGlobalTheme(':root', colorVars, defaultCSSColors);
// @ts-expect-error
createGlobalTheme(':root', buttonsVars, defaultCSSButtons);
The expect error here is caused by #223
When I run gatsby I get the following error:
ERROR #98123 WEBPACK
Generating development JavaScript bundle failed
Module build failed (from ../../node_modules/gatsby/node_modules/mini-css-extract-plugin/dist/loader.js):
Error: Didn't get a result from child compiler
at /Users/phil/Code/newrade-core/node_modules/gatsby/node_modules/mini-css-extract-plugin/dist/loader.js:311:23
at /Users/phil/Code/newrade-core/node_modules/webpack/lib/Compiler.js:548:11
at /Users/phil/Code/newrade-core/node_modules/webpack/lib/Compiler.js:1118:17
at Hook.eval [as callAsync] (eval at create (/Users/phil/Code/newrade-core/node_modules/tapable/lib/HookCodeFactory.js:33:10),
<anonymous>:6:1)
at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (/Users/phil/Code/newrade-core/node_modules/tapable/lib/Hook.js:18:14)
at /Users/phil/Code/newrade-core/node_modules/webpack/lib/Compiler.js:1114:33
at finalCallback (/Users/phil/Code/newrade-core/node_modules/webpack/lib/Compilation.js:2249:11)
at /Users/phil/Code/newrade-core/node_modules/webpack/lib/Compilation.js:2540:11
at Hook.eval [as callAsync] (eval at create (/Users/phil/Code/newrade-core/node_modules/tapable/lib/HookCodeFactory.js:33:10),
<anonymous>:6:1)
at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (/Users/phil/Code/newrade-core/node_modules/tapable/lib/Hook.js:18:14)
at /Users/phil/Code/newrade-core/node_modules/webpack/lib/Compilation.js:2533:38
at eval (eval at create (/Users/phil/Code/newrade-core/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:15:1)
at fn (/Users/phil/Code/newrade-core/node_modules/webpack/lib/Compilation.js:464:9)
at _next0 (eval at create (/Users/phil/Code/newrade-core/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:11:1)
at eval (eval at create (/Users/phil/Code/newrade-core/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:24:1)
at fn (/Users/phil/Code/newrade-core/node_modules/webpack/lib/Compilation.js:464:9)
File: src/design-system/theme.css.ts
failed Building development bundle - 42.797s
ERROR in ./src/design-system/theme.css.ts
Module build failed (from
../../node_modules/@vanilla-extract/webpack-plugin/loader/dist/vanilla-extract-webpack-plugin-loader.cjs.js):
ModuleBuildError: Module build failed (from ../../node_modules/gatsby/node_modules/mini-css-extract-plugin/dist/loader.js):
Error: Didn't get a result from child compiler
at /Users/phil/Code/newrade-core/node_modules/gatsby/node_modules/mini-css-extract-plugin/dist/loader.js:311:23
at /Users/phil/Code/newrade-core/node_modules/webpack/lib/Compiler.js:548:11
at /Users/phil/Code/newrade-core/node_modules/webpack/lib/Compiler.js:1118:17
at Hook.eval [as callAsync] (eval at create (/Users/phil/Code/newrade-core/node_modules/tapable/lib/HookCodeFactory.js:33:10),
<anonymous>:6:1)
at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (/Users/phil/Code/newrade-core/node_modules/tapable/lib/Hook.js:18:14)
at /Users/phil/Code/newrade-core/node_modules/webpack/lib/Compiler.js:1114:33
at finalCallback (/Users/phil/Code/newrade-core/node_modules/webpack/lib/Compilation.js:2249:11)
at /Users/phil/Code/newrade-core/node_modules/webpack/lib/Compilation.js:2540:11
at Hook.eval [as callAsync] (eval at create (/Users/phil/Code/newrade-core/node_modules/tapable/lib/HookCodeFactory.js:33:10),
<anonymous>:6:1)
at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (/Users/phil/Code/newrade-core/node_modules/tapable/lib/Hook.js:18:14)
at /Users/phil/Code/newrade-core/node_modules/webpack/lib/Compilation.js:2533:38
at eval (eval at create (/Users/phil/Code/newrade-core/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:15:1)
at fn (/Users/phil/Code/newrade-core/node_modules/webpack/lib/Compilation.js:464:9)
at _next0 (eval at create (/Users/phil/Code/newrade-core/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:11:1)
at eval (eval at create (/Users/phil/Code/newrade-core/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:24:1)
at fn (/Users/phil/Code/newrade-core/node_modules/webpack/lib/Compilation.js:464:9)
at processResult (/Users/phil/Code/newrade-core/node_modules/webpack/lib/NormalModule.js:701:19)
at /Users/phil/Code/newrade-core/node_modules/webpack/lib/NormalModule.js:807:5
at /Users/phil/Code/newrade-core/node_modules/loader-runner/lib/LoaderRunner.js:399:11
at /Users/phil/Code/newrade-core/node_modules/loader-runner/lib/LoaderRunner.js:195:20
at context.callback (/Users/phil/Code/newrade-core/node_modules/loader-runner/lib/LoaderRunner.js:124:13)
at /Users/phil/Code/newrade-core/node_modules/gatsby/node_modules/mini-css-extract-plugin/dist/loader.js:311:14
at /Users/phil/Code/newrade-core/node_modules/webpack/lib/Compiler.js:548:11
at /Users/phil/Code/newrade-core/node_modules/webpack/lib/Compiler.js:1118:17
at Hook.eval [as callAsync] (eval at create (/Users/phil/Code/newrade-core/node_modules/tapable/lib/HookCodeFactory.js:33:10),
<anonymous>:6:1)
at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (/Users/phil/Code/newrade-core/node_modules/tapable/lib/Hook.js:18:14)
at /Users/phil/Code/newrade-core/node_modules/webpack/lib/Compiler.js:1114:33
at finalCallback (/Users/phil/Code/newrade-core/node_modules/webpack/lib/Compilation.js:2249:11)
at /Users/phil/Code/newrade-core/node_modules/webpack/lib/Compilation.js:2540:11
at Hook.eval [as callAsync] (eval at create (/Users/phil/Code/newrade-core/node_modules/tapable/lib/HookCodeFactory.js:33:10),
<anonymous>:6:1)
at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (/Users/phil/Code/newrade-core/node_modules/tapable/lib/Hook.js:18:14)
at /Users/phil/Code/newrade-core/node_modules/webpack/lib/Compilation.js:2533:38
@ ./gatsby-wrap-element.tsx 10:0-39 11:0-59 71:26-36
@ ./gatsby-browser.jsx 8:0-52 20:42-53
@ ./.cache/api-runner-browser-plugins.js 115:10-42
@ ./.cache/api-runner-browser.js 4:16-55
@ ./.cache/app.js 10:0-65 27:87-31:1 35:20-29 48:0-14 112:19-28 146:6-15 27:0-31:2
1 ERROR in child compilations (Use 'stats.children: true' resp. '--stats-children' for more details)
webpack compiled with 2 errors
What bothers me is I have 0 information in the stack trace to find out what is going on...
with DEBUG=vanilla-extract:loader*
I see no error either:
Is there a way to get better error information ?
I might have to create a repro here... unless you can tell me what to look for
Creating a repro is going to take me a good amount of time, it's a 20 packages monorepo so I'd have to create at least 1 ui lib, 1 gatsby site and 1 type repo where the shape of my design system lives
Output of npx envinfo --system --npmPackages @vanilla-extract/css,@vanilla-extract/webpack-plugin,@vanilla-extract/esbuild-plugin,@vanilla-extract/vite-plugin,@vanilla-extract/sprinkles,webpack,esbuild,vite --binaries --browsers
:
System:
OS: macOS 11.4
CPU: (8) arm64 Apple M1
Memory: 1.80 GB / 16.00 GB
Shell: 3.2.57 - /bin/bash
Binaries:
Node: 16.4.1 - ~/.nvm/versions/node/v16.4.1/bin/node
Yarn: 1.22.10 - /opt/homebrew/bin/yarn
npm: 7.18.1 - ~/.nvm/versions/node/v16.4.1/bin/npm
Browsers:
Brave Browser: 91.1.25.68
Chrome: 91.0.4472.114
Safari: 14.1.1
PS. I'm migrating from treat
When attempting to import compiled components from our node_modules
folder I end up with either class="undefined"
or simply a blank class
for any Vanilla Extract classNames
that are being used as dependencies from node_modules
.
I've modified the Vanilla Extract demo with a very very simple repro here: https://codesandbox.io/s/eager-turing-z7cw1?file=/src/test.css.js
Output of npx envinfo --system --npmPackages @vanilla-extract/css,@vanilla-extract/webpack-plugin,@vanilla-extract/esbuild-plugin,@vanilla-extract/vite-plugin,@vanilla-extract/sprinkles,webpack,esbuild,vite --binaries --browsers
:
System:
OS: macOS 11.3.1
CPU: (16) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
Memory: 90.09 MB / 16.00 GB
Shell: 5.8 - /bin/zsh
Binaries:
Node: 14.15.4 - ~/.nvm/versions/node/v14.15.4/bin/node
Yarn: 1.22.10 - ~/.nvm/versions/node/v14.15.4/bin/yarn
npm: 6.14.11 - ~/.nvm/versions/node/v14.15.4/bin/npm
Browsers:
Chrome: 90.0.4430.212
Firefox: 78.0.1
Safari: 14.1
Note: using npm
not yarn
these days, all testing done in Chrome.
Running vite on a windows machine and having a file starting with the letter 't' result in 404. In my example I'm using theme.css.ts, on mac this all works fine. However running the same example on Windows results in the following virtual file not found "http://localhost:3000/@id/project/srcheme.css.ts.vanilla.css?hash=xxx". The problem here is tab \t is somewhere being cast to a tab, thus the correct url should be src/theme.css
not srcheme.css
. (Files starting with 's' don't cause any problems.)
I tried to debug (and fix) the issue, but thinking this is not a wonderfull solution π
How I managed to fix it π
Replacing
https://github.com/seek-oss/vanilla-extract/blob/master/packages/vite-plugin/src/index.ts#L23
const { fileName, source } = getSourceFromVirtualCssFile(id);
With
const { fileName, source } = getSourceFromVirtualCssFile(id.replace(/\t/g, '\/t');
Happy to make a pr and follow advice.
Got an example repo, run yarn
then yarn start
on windows platform.
https://bitbucket.org/Saartje87/vanilla-extract/src/master/
Output of npx envinfo --system --npmPackages @vanilla-extract/css,@vanilla-extract/webpack-plugin,@vanilla-extract/esbuild-plugin,@vanilla-extract/vite-plugin,@vanilla-extract/sprinkles,webpack,esbuild,vite --binaries --browsers
:
System:
OS: Windows 10 10.0.19043
CPU: (16) x64 Intel(R) Core(TM) i7-10870H CPU @ 2.20GHz
Memory: 5.90 GB / 15.83 GB
Binaries:
Node: 14.16.0 - C:\Program Files\nodejs\node.EXE
Yarn: 1.22.10 - ~\AppData\Roaming\npm\yarn.CMD
npm: 7.7.5 - C:\Program Files\nodejs\npm.CMD
Browsers:
Edge: Spartan (44.19041.964.0), Chromium (90.0.818.56)
Internet Explorer: 11.0.19041.1
npmPackages:
@vanilla-extract/css: ^0.4.3 => 0.4.3
@vanilla-extract/sprinkles: ^0.2.2 => 0.2.2
@vanilla-extract/vite-plugin: ^0.1.1 => 0.1.1
vite: ^2.2.4 => 2.2.4
Previously: #213
I'm in the same boat as @jimkyndemeyer where I'd like to use TypeScript without requiring Babel. I think a simple way to achieve this would be to make a webpack loader for vanilla-extract that allows for users to chain loaders like:
{
test: /\.css\.ts$/,
use: [
"ts-loader",
"@vanilla-extract/loader"
]
},
I'd love to hear your thoughts on this.
Reading the docs I see how to get set up and seems pretty straightforward for one project.
How do you recommend setting this up where the theme and CSS would be in project-one which is published and then consumed by project-two/three/etc (think design system)? I could see either needing to compile before publishing or needing to have any consumer project adjust their build setup. Do you have any guides for this type of setup?
Hi, I am excited about having a new CSS in Js library with zero runtime cost.
Does this library can be used with other bundlers or is it only webpack specific?
I would like to be able to run it on a more minimal project with esbuild for example.
Not something that can hold me back to try it, I can still try it with webpack, but I am opening a low priority issue just to let you know
Thanks for your effort, appreciate it
I have this rule
export const required = style({
":before": {
content: "*",
marginRight: vars.space["1x"]
}
});
But the rule is not coming through in the css.
Here is a codesanbox that shows the problem.
Output of npx envinfo --system --npmPackages @vanilla-extract/css,@vanilla-extract/webpack-plugin,@vanilla-extract/esbuild-plugin,@vanilla-extract/vite-plugin,@vanilla-extract/sprinkles,webpack,esbuild,vite --binaries --browsers
:
System:
OS: macOS 11.4
CPU: (8) x64 Apple M1
Memory: 36.04 MB / 16.00 GB
Shell: 5.8 - /bin/zsh
Binaries:
Node: 14.16.0 - ~/.volta/tools/image/node/14.16.0/bin/node
Yarn: 1.22.0 - ~/.volta/tools/image/yarn/1.22.0/bin/yarn
npm: 6.14.11 - ~/.volta/tools/image/node/14.16.0/bin/npm
Browsers:
Chrome: 91.0.4472.114
Firefox: 89.0
Safari: 14.1.1
While developing code with treat and vanilla, I experience big problem with RAM usage
After saving .treat.ts or .css.ts files repeatedly, the node process leak memory and grow to all heap size available causing a crash.
For example, see the ram usage of the node process a couple of saves:
And after 10 more saves:
The first node process goes from 296MB to 400MB with 0 code change... just pressing enter and saving (triggering new build check)
https://github.com/newrade/vanilla-treat-repro
Output of npx envinfo --system --npmPackages @vanilla-extract/css,@vanilla-extract/webpack-plugin,@vanilla-extract/esbuild-plugin,@vanilla-extract/vite-plugin,@vanilla-extract/sprinkles,webpack,esbuild,vite --binaries --browsers
:
System:
OS: macOS 11.4
CPU: (8) arm64 Apple M1
Memory: 76.94 MB / 16.00 GB
Shell: 3.2.57 - /bin/bash
Binaries:
Node: 16.5.0 - ~/.nvm/versions/node/v16.5.0/bin/node
Yarn: 1.22.10 - /opt/homebrew/bin/yarn
npm: 7.19.1 - ~/.nvm/versions/node/v16.5.0/bin/npm
Browsers:
Brave Browser: 91.1.25.68
Chrome: 91.0.4472.114
Safari: 14.1.1
npmPackages:
@vanilla-extract/css: ^1.1.0 => 1.1.0
webpack: ^5 => 5.44.0
I bootstrapped an app with create-snowpack-app
using the preact-typescript
template. whenever I try to use the style
function, I get this weird error:
Unhandled Runtime Error
Script error.
Source:
no source file
when I check the browser console, this is whats there
SyntaxError: Importing binding name 'parse' is not found.
not sure at what level this is happening, whether its a preact thing or what, not sure how that would change things though. I have the snowpack plugin installed.
I made this demo repo which is a 1:1 to what I have, steps to see error after pulling down the repo:
$ yarn install
$ yarn start
its a mono repo, but if you want you can cd packages/client
then run those steps above so that its identical to a standalone repo.
System:
OS: macOS 11.4
CPU: (8) x64 Intel(R) Core(TM) i7-6700HQ CPU @ 2.60GHz
Memory: 2.19 GB / 16.00 GB
Shell: 5.8 - /usr/local/bin/zsh
Binaries:
Node: 16.4.2 - ~/.asdf/installs/nodejs/16.4.2/bin/node
Yarn: 1.22.4 - ~/.asdf/shims/yarn
npm: 7.18.1 - ~/.asdf/installs/nodejs/16.4.2/bin/npm
Browsers:
Chrome: 91.0.4472.114
Firefox Developer Edition: 90.0
Safari: 14.1.1
Safari Technology Preview: 15.0
When using vanilla-extract with storybook, it seems to fail when I insert more than one media query into style
(one works fine).
Branch:
https://github.com/namliw/humds/tree/multiple-media-queries
Media queries are used here:
https://github.com/namliw/humds/blob/multiple-media-queries/src/components/PictoCard/PictoCardGroup/styles.css.ts
Published storybook:
https://60fe2eb8cdf879003992175e-lqlpkrsdkv.chromatic.com/?path=/story/molecules-pictocard-pictocardgroup--explorer
Created a sandbox:
Created another app using create-react-app
:
App
component with the same code as the sandbox, then ran yarn start
and it worksstorybook
, it fails with yarn storybook
but still works with yarn start
(probably misconfigured since it plain isn't working, as opposed to the other repo which is mostly working) System:
OS: macOS 11.5
CPU: (16) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
Memory: 311.64 MB / 32.00 GB
Shell: 5.8 - /bin/zsh
Binaries:
Node: 14.17.0 - ~/.nvm/versions/node/v14.17.0/bin/node
Yarn: 1.22.5 - ~/.asdf/shims/yarn
npm: 6.14.13 - ~/.nvm/versions/node/v14.17.0/bin/npm
Browsers:
Brave Browser: 91.1.26.77
Chrome: 92.0.4515.107
Firefox: 89.0.2
Safari: 14.1.2
npmPackages:
@vanilla-extract/css: ^1.1.2 => 1.1.2
@vanilla-extract/webpack-plugin: ^1.0.3 => 1.0.3
webpack: ^5.47.0 => 5.47.0
Collab with @namliw
Hi, Thank you for creating such a cool CSS pre-processor. Seeing that vanilla-extract loves typescript, just like Angular does I was very interested in getting it working with an Angular project. I customised the Webpack settings as Angular CLI tries to own the Webpack config, made necessary changes in angular.json(the first two files) and applied necessary changes in the webpack.config.js but the project is not compiling post the changes
Without this change, the errors are even more.
Hey Team,
Thanks for vanilla-extract. π
The library makes sense for users who want to use CSS modules and stay close to native CSS but leverage type safety. From my understanding it looks like a promising css architecture to integrate with libraries using css design tokens.
Is there a support planned for Rollup through a rollup plugin ?
Sometimes media queries appear to be in the wrong order in the CSS:
Here are the declarations (I'd expect same order as when created?):
What I find odd about this is that changing the media queries to remove the screen and
part sometimes appears to fix it.
But then changing other declarations may cause it to return. Perhaps some funny shenanigans are happening with order when objects are merged to cloned?
I'm having trouble isolating a small consistent reproduction case although I can reproduce reliably in my project.
I'm using vanilla, vanilla extract here with no other abstractions apart from a few variables for tokens. I'm working in a mono repo with a Gatsby site where my components are stored in a different package.
Output of npx envinfo --system --npmPackages @vanilla-extract/css,@vanilla-extract/webpack-plugin,@vanilla-extract/esbuild-plugin,@vanilla-extract/vite-plugin,@vanilla-extract/sprinkles,webpack,esbuild,vite --binaries --browsers
:
System:
OS: Linux 4.4 Ubuntu 20.04 LTS (Focal Fossa)
CPU: (12) x64 AMD Ryzen 5 3600 6-Core Processor
Memory: 4.84 GB / 15.95 GB
Container: Yes
Shell: 5.8 - /usr/bin/zsh
Binaries:
Node: 12.16.3 - ~/.nvm/versions/node/v12.16.3/bin/node
Yarn: 1.22.10 - ~/.nvm/versions/node/v12.16.3/bin/yarn
npm: 6.14.4 - ~/.nvm/versions/node/v12.16.3/bin/npm
Hello π
Very excited about vanilla-extract and wanted to give it a try in Framer with esbuild.
Unfortunately, I'm having some difficulties with the output. I wonder if this could be a bug with the esbuild plugin, or perhaps a mistake on my end!!
Here are my files:
// definitions.ts
import { createThemeVars } from "@vanilla-extract/css"
export const theme = createThemeVars({
color: {
tint: null,
tintDark: null,
},
})
// dark.css.ts
import { createTheme } from "@vanilla-extract/css"
import { theme } from "./definitions"
export const dark = createTheme(
theme,
{
color: {
tint: "#0099ff",
tintDark: "#0088ff",
},
},
"dark-theme"
)
Elsewhere, I import dark
and consume it in react:
import { dark } from "./dark.css"
// ...
<div className={dark}>
My output from esbuild is then:
/* vanilla-extract-css-ns:vekter/../fresco/src/tokens/colors/theme/dark.css.ts.vanilla.css?source=LmRhcmtfZGFyay10aGVtZV9fMWt1cWlxMTAgewogIG51bGw6ICMwMDg4ZmY7Cn0= */
.dark_dark-theme__1kuqiq10 {
null: #0088ff;
}
Dependencies:
"@vanilla-extract/css": "^0.3.0",
"@vanilla-extract/esbuild-plugin": "^0.1.2",
When using with SvelteKit after configuring vite it throws this error:
New styles cannot be registered dynamically after initial boot. This is to ensure that styles are statically extractible.
If I have, for example, a list:
<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>
Normally I would create a class for the <ul class="list" />
and then target the items with .list > li
.
With this library - would I be better off using globalStyle('${list} > li', {})
or applying a class to each <li />
?
Seems like even if the component that uses vanilla-extract is static, if the pages that use that component is dynamic then vanilla-extract spits out an error.
error - ./src/components/article-section/styles.css.ts
VanillaExtractError: @vanilla-extract/webpack-plugin: An error occured during compilation:
Error: New styles cannot be registered dynamically after initial boot. This is to ensure that styles are statically extractible.
at runMicrotasks (<anonymous>)
event - compiled successfully
next.config.js:
const { VanillaExtractPlugin } = require('@vanilla-extract/webpack-plugin');
const { getGlobalCssLoader } = require('next/dist/build/webpack/config/blocks/css/loaders');
const MiniCssExtractPlugin = require('next/dist/build/webpack/plugins/mini-css-extract-plugin/src').default;
module.exports = {
future: {
webpack5: true,
},
webpack: (config, { dev, isServer, ...options }) => {
// Fixes npm packages that depend on `fs` module
if (!isServer) {
config.node = {
fs: 'empty'
}
}
// --- vanilla-extract config ---
// based on: https://github.com/seek-oss/vanilla-extract/issues/4#issuecomment-810842869
config.module.rules.push({
test: /\.css$/i,
sideEffects: true,
use: dev
? getGlobalCssLoader(
{
assetPrefix: options.config.assetPrefix,
future: {
webpack5: true,
},
isClient: !isServer,
isServer,
isDevelopment: dev,
},
[],
[]
)
: [MiniCssExtractPlugin.loader, 'css-loader'],
});
config.plugins.push(
new VanillaExtractPlugin()
);
if (!dev) {
config.plugins.push(
new MiniCssExtractPlugin({
filename: 'static/css/[contenthash].css',
chunkFilename: 'static/css/[contenthash].css',
ignoreOrder: true,
})
);
}
config.resolve.extensions = ['.js', '.jsx', '.ts', '.tsx', '.css', '.css.ts'];
// ------------------------------
return config;
},
async redirects() {
return [
{ source: '/', destination: '/index', permanent: true },
]
}
};
package.json
{
"name": "gitwiki",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"no-telemetry": "next telemetry disable",
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint:types": "tsc --noEmit"
},
"devDependencies": {
"@types/node": "^14.14.13",
"@types/react": "^17.0.0",
"@vanilla-extract/babel-plugin": "^0.2.1",
"@vanilla-extract/css": "^0.2.0",
"@vanilla-extract/webpack-plugin": "^0.2.0",
"css-loader": "^5.2.4",
"next": "^9.5.5",
"react": "^16.14.0",
"react-dom": "^16.14.0",
"typescript": "^4.1.3"
},
"dependencies": {
"@mdx-js/runtime": "^1.6.18",
"express-graphql": "^0.11.0",
"graphql": "^15.3.0",
"graphql-request": "^3.2.0",
"swr": "^0.3.6"
}
}
Potentially help developers evaluating vanilla-extract for their next project.
According to the README, in order to disable runtime styles, I need to add this to the jest setupTests
file
import '@vanilla-extract/css/disableRuntimeStyles';
npm install @vanilla-extract/css
node
require('@vanilla-extract/css/disableRuntimeStyles') // Cannot find module '@vanilla-extract/css/disableRuntimeStyles'
The files section of @vanilla-extract/css
has a number of files that are not actually pointing to a correct location:
"files": [
"/dist",
"/recipe",
"/adapter",
"/transformCss",
"/fileScope",
"/disableRuntimeStyles"
],
Output of npx envinfo --system --npmPackages @vanilla-extract/css,@vanilla-extract/webpack-plugin,@vanilla-extract/esbuild-plugin,@vanilla-extract/vite-plugin,@vanilla-extract/sprinkles,webpack,esbuild,vite --binaries --browsers
:
System:
OS: macOS 11.4
CPU: (8) x64 Apple M1
Memory: 36.04 MB / 16.00 GB
Shell: 5.8 - /bin/zsh
Binaries:
Node: 14.16.0 - ~/.volta/tools/image/node/14.16.0/bin/node
Yarn: 1.22.0 - ~/.volta/tools/image/yarn/1.22.0/bin/yarn
npm: 6.14.11 - ~/.volta/tools/image/node/14.16.0/bin/npm
Browsers:
Chrome: 91.0.4472.114
Firefox: 89.0
Safari: 14.1.1
I was really looking forward to see what you have been working on and I am super excited to try it out in my project that currently uses Emotion :)
Currently the createVar
function generates a variable name and then returns it wrapped in var(...)
. This makes it easier to reference a scoped CSS var in style
blocks, but at the same time makes it a bit trickier to set its value outside of a .css.ts
file.
Would you consider adding a new function, for example called createVarName
, that just returns a variable name?
Here is a pseudo-example of usage:
// component.css.ts
import { createVarName, style } from '@vanilla-extract/css';
export const positionVar = createVarName();
export const box = style({
transform: `translate3d(var(${positionVar}), 0, 0)`,
});
// component.ts
import { useRef, useState } from 'react';
import * as styles from './component.css';
export default function SomeComponent() {
const boxRef = useRef<HTMLDivElement>(null);
const [currentIndex, setCurrentIndex] = useState(0);
useLayoutEffect(() => {
if (boxRef.current) {
boxRef.current.style.setProperty(
styles.positionVar,
`${currentIndex * 1000}px`,
);
}
}, [currentIndex]);
return (
<div className={styles.box} ref={boxRef}>
...
</div>
);
}
When i run webpack, i have some error.
Module parse failed: Unexpected token (4:7)
File was processed with these loaders:
Since there is way to export functions from css.ts, why not to add possibility to create classnames string based on some runtime condition? It should enforce encapsulation of styles.
export const buttonStyles = dynamicVariants(style({
//default styles
background: 'white',
}),{
//styles variants
primary: style({background: 'green'}),
disabled: style({
background: 'gray',
cursor: 'unset',
})
})
And then...
import {buttonStyles} from './styles.css.ts'
function SomeButton({primary, disabled}: {primary: boolean, disabled: boolean}) {
return <button className={buttonStyles({primary, disabled})} />
}
Hello!
First and foremost, thanks for the library! If you feel like this better fits into Discussions, feel free to move it there.
I wanted to refactor a project of mine and saw the library pop-up on Twitter so I gave it a try: https://github.com/LekoArts/gatsby-source-tmdb/tree/7701461beb678b3ca2534e03b4c6df1aeea818a0/example
So here are some loosely structured thoughts about using it the first time. I didn't hit any bugs, only usage limitations and some confusion around docs.
globalStyle
I'd also like to use element selectors like h1
. I needed to define the global styles for headings inside a normal CSS file:hover:after
pseudo selector so I also had to revert to a normal CSS file for thatselectors
portion in the docs was unclear to me, at the beginning I got a lot of error messages as I e.g. tried to use element selectors or classnames there. Only later it made click that it only affects the current style/class and that you can use that with a parenticon-fill-color
in the icon and then in the CSS the --icon-fill-color: 'newColor'
is reassigned instead of overriding the fill
itself. I probably didn't do that as the docs had part of that pattern only here: https://github.com/seek-oss/vanilla-extract#createvarexport const exampleStyle = style({
color: 'white',
children: {
div: {
color: 'black'
}
}
})
Trying to run Jest tests creates an error:
β Test suite failed to run
Styles were unable to be assigned to a file. This is generally caused by one of the following:
- You may have created styles outside of a '.css.ts' context
- You may have incorrect configuration. See https://vanilla-extract.style/documentation/setup
1 | import { style } from '@vanilla-extract/css';
2 |
> 3 | export const button = style({
.....
I've tried using import '@vanilla-extract/css/disableRuntimeStyles'
in my setupFilesAfterEnv
file, but it doesn't seem to effect anything. I followed the webpack tutorial, and everything else seems to be working. Just broken on unit tests.
Output of npx envinfo --system --npmPackages @vanilla-extract/css,@vanilla-extract/webpack-plugin,@vanilla-extract/esbuild-plugin,@vanilla-extract/vite-plugin,@vanilla-extract/sprinkles,webpack,esbuild,vite --binaries --browsers
:
System:
OS: macOS 11.4
CPU: (12) x64 Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
Memory: 1.43 GB / 16.00 GB
Shell: 5.8 - /bin/zsh
Binaries:
Node: 14.17.1 - ~/.nvm/versions/node/v14.17.1/bin/node
npm: 7.19.0 - ~/.nvm/versions/node/v14.17.1/bin/npm
Browsers:
Chrome: 91.0.4472.114
Firefox: 90.0
Safari: 14.1.1
npmPackages:
@vanilla-extract/css: ^1.1.2 => 1.1.2
@vanilla-extract/webpack-plugin: ^1.0.3 => 1.0.3
webpack: ^5.11.1 => 5.44.
We have setElementVar
to set a var on a DOM element. But how about a more declarative way to assign the var using inline styles? I tried to do something like
const currentValue = createVar();
const style = {[currentValue]: `${100 * percentage}%`};
return <div style={style} />
which obviously doesn't work because currentValue
is "var(--currentValue-xyz)"
. Is there another way to do this?
Error: Exported variable 'Box' has or is using name 'ResponsiveArray' from external module "node_modules/@vanilla-extract/sprinkles/dist/declarations/src/types" but cannot be named.
import { createAtomicStyles, createAtomsFn } from '@vanilla-extract/sprinkles';
const colorStyles = createAtomicStyles({
conditions: {
lightMode: {},
darkMode: { '@media': '(prefers-color-scheme: dark)' }
},
defaultCondition: 'lightMode',
responsiveArray: ['lightMode', 'darkMode'],
properties: {
// ...
}
});
export const atoms = createAtomsFn(colorStyles);
import { createBox } from 'dessert-box';
import { atoms } from '../../theme/atoms.css';
export const Box = createBox(atoms);
export { atoms };
The error is the same if I don't use desert-box and copy the code into my project instead.
The type error goes away when I add export
to ResponsiveArray
.
Output of npx envinfo --system --npmPackages @vanilla-extract/css,@vanilla-extract/webpack-plugin,@vanilla-extract/esbuild-plugin,@vanilla-extract/vite-plugin,@vanilla-extract/sprinkles,webpack,esbuild,vite --binaries --browsers
:
System:
OS: macOS 10.15.7
CPU: (12) x64 Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
Memory: 294.11 MB / 32.00 GB
Shell: 3.2.57 - /bin/bash
Binaries:
Node: 16.4.2 - /usr/local/bin/node
Yarn: 1.22.10 - /usr/local/bin/yarn
npm: 7.18.1 - /usr/local/bin/npm
Watchman: 2021.06.07.00 - /usr/local/bin/watchman
Browsers:
Chrome: 91.0.4472.164
Safari: 14.1.2
npmPackages:
@vanilla-extract/css: ^1.1.2 => 1.1.2
@vanilla-extract/esbuild-plugin: ^1.1.0 => 1.1.0
@vanilla-extract/sprinkles: ^0.4.3 => 0.4.3
I have successfully set up vanilla-extract
using webpack and my sample app works in the browser! π
However, my issue is that VSCode fails to correctly resolve .css.ts
imports and therefore I lose the power of autocomplete/inline type checking!
An import path cannot end with a '.ts' extension. Consider importing './atoms.css.js' instead.
The typescript language server in VSCode doesn't like it when imports end with .ts
and there doesn't appear to be a way to fix this.
This is a long-standing issue (specifically affecting deno users) but appears to affect
vanilla-extract
as well. See microsoft/TypeScript#27481
If I import ./atoms.css
(or ./atoms.css.js
) then VSCode correctly picks up the types; however, webpack no longer resolves the file correctly, causing the build to break.
How can I reconcile these two worlds to make them both happy at the same time?
JavaScript files in the dist
directory use ES2015 syntax, requiring clients to transpile library code down to ES5 format.
This issue is only slightly inconvenient, but more importantly it is not discoverable for a developer who primarily uses a modern browser for development. I only discovered it by accident while manually inspecting my bundle.
As you know, a common pattern (performance optimization) when configuring Webpack's babel-loader
is to ignore the node_modules
directory, e.g.
{ test: /\.js$/, exclude: /node_modules/, use: ["babel-loader"] }
Personally, my workaround is this, but it's sort of a bummer:
{
test: /vanilla-extract\/css\/dist\/.*\.js$/,
use: [{ loader: "babel-loader", options: { presets: ["@babel/env"] } }]
}
Here are some examples:
$ cat node_modules/@vanilla-extract/css/dist/vanilla-extract-css.browser.cjs.js | grep const
const stylesheets = {};
const localClassNames = new Set();
const fileScopeId = packageName ? `${packageName}${filePath}` : filePath;
const styleEl = document.createElement('style');
const browserRuntimeAdapter = {
const css = transformCss_dist_vanillaExtractCssTransformCss.transformCss({
const stylesheet = getStylesheet(fileScope);
const existingRuleCount = stylesheet.cssRules.length;
for (const rule of css) {
const parts = debugId ? [debugId] : [];
const {
const matches = filePath.match(/(?<dir>[^\/\\]*)?[\/\\]?(?<file>[^\/\\]*)\.css\.(ts|js|tsx|jsx)$/);
const {
const refCount = fileScope_dist_vanillaExtractCssFileScope.getAndIncrementRefCounter().toString(36);
const {
const fileScopeHash = hash__default['default'](packageName ? `${packageName}${filePath}` : filePath);
const devPrefix = getDevPrefix(debugId);
const normaliseObject = obj => _private.walkObject(obj, () => '');
const theDiff = deepObjectDiff.diff(normaliseObject(contract), normaliseObject(tokens));
const valid = Object.keys(theDiff).length === 0;
const whitespace = [...Array(nesting).keys()].map(() => ' ').join('');
const line = `${type ? type : ' '}${whitespace}${value}`;
const lines = [];
const innerNesting = nesting + 1;
const keys = Object.keys(diff).sort();
for (const key of keys) {
const value = diff[key];
const refCount = fileScope_dist_vanillaExtractCssFileScope.getAndIncrementRefCounter().toString(36);
const {
const fileScopeHash = hash__default['default'](packageName ? `${packageName}${filePath}` : filePath);
const varName = process.env.NODE_ENV !== 'production' && debugId ? `${debugId}__${fileScopeHash}${refCount}` : `${fileScopeHash}${refCount}`;
const cssVarName = cssesc__default['default'](varName.match(/^[0-9]/) ? `_${varName}` : varName, {
const varSetters = {};
const {
const shouldCreateVars = Boolean(!arg3);
const themeVars = shouldCreateVars ? createThemeContract(arg2) : arg2;
const tokens = shouldCreateVars ? arg2 : arg3;
const themeClassName = generateIdentifier(typeof arg2 === 'object' ? arg3 : arg2);
const vars = typeof arg2 === 'object' ? createGlobalTheme(themeClassName, arg1, arg2) : createGlobalTheme(themeClassName, arg1);
const className = generateIdentifier(debugId);
const fontFamily = `"${cssesc__default['default'](generateIdentifier(debugId), {
const name = cssesc__default['default'](generateIdentifier(debugId), {
const data = args[0];
const mapData = args[1];
const debugId = args[2];
const classMap = {};
for (const key in data) {
const styleMap = args[0];
const debugId = args[1];
const classMap = {};
for (const key in styleMap) {
for (const className of classNames) {
const set = new Set();
N/A
It looks like thereβs a typo in the readmeβs code snippet where you show a composeStyles example
// styles.css.ts
import { style, composeStyles } from '@vanilla-extract/css';
import { atoms } from './atoms.css.ts';
export const container = composeStyles(
atoms({
display: 'flex',
paddingX: 'small'
}) // should there be a comma here?
style({
':hover': {
outline: '2px solid currentColor'
}
})
);
Can I style pseudo classes like ::before
and ::after
? If so it would be nice with an example in the docs.
Using Sprinkles I want to add property keys similar to this:
properties: {
width: {
"1/2": "50%"
}
}
It works fine except in combination with conditions
like this:
conditions: {
mobile: {},
hover: { selector: "&:hover" }
},
Error is:
Selectors must target the ampersand character ('&'), which refers to the generated class name, e.g. '&:nth-child(2n)'
Looks to be a false positive, or something is mungeing the selector.
It could be all selectors with ampersands and it could be more characters in property keys than just /
that cause this.
Note Don't be tempted to say change the property key (I will for now) but I think fractions are super sensible in a lot of cases. Another reason is I'm developing something to consumption by other devs and I'd like to stick kinda close to the tailwind naming conventions for some keys just to aid with familiarity and documentation.
https://codesandbox.io/s/winter-hill-j2tfb?file=/src/sprinkles.css.ts
Output of npx envinfo --system --npmPackages @vanilla-extract/css,@vanilla-extract/webpack-plugin,@vanilla-extract/esbuild-plugin,@vanilla-extract/vite-plugin,@vanilla-extract/sprinkles,webpack,esbuild,vite --binaries --browsers
:
System:
OS: Linux 4.4 Ubuntu 20.04 LTS (Focal Fossa)
CPU: (12) x64 AMD Ryzen 5 3600 6-Core Processor
Memory: 4.84 GB / 15.95 GB
Container: Yes
Shell: 5.8 - /usr/bin/zsh
Binaries:
Node: 12.16.3 - ~/.nvm/versions/node/v12.16.3/bin/node
Yarn: 1.22.10 - ~/.nvm/versions/node/v12.16.3/bin/yarn
npm: 6.14.4 - ~/.nvm/versions/node/v12.16.3/bin/npm
I've testing this library in a razzle setup, works pretty well. I loved it.
Following the readme of sprinkles package, I've read that you can use tailwind color values in colorStyles definitions, then I wrote a normalized object of color and provided to createAtomicStyles
function, see the example below:
import { createAtomicStyles, createAtomsFn } from "@vanilla-extract/sprinkles";
import * as colors from "tailwindcss/colors";
type ColorHue = keyof typeof colors["rose"];
type ColorNames = keyof Omit<typeof colors, "black" | "white">;
type ThemeColors = `${ColorNames}${ColorHue}`;
// here we transform { rose: { 50: "#hex", 100: "#hex" } } into { rose50: "#hex", rose100: "#hex" }
const normalizedColors: { [K in ThemeColors]: string } = Object.entries(colors)
.map(([key, color]) => {
const normalized = Object.entries(color).map(([hue, value]) => {
return [`${key}${hue}`, value];
});
return Object.fromEntries(normalized);
})
.reduce((acc, obj) => ({ ...acc, ...obj }), {});
// and finally we add black and white colors
const withBlackAndWhite = {
...normalizedColors,
black: "#000000",
white: "#ffffff",
};
export const colorStyles = createAtomicStyles({
conditions: {
lightMode: { "@media": "(prefers-color-scheme: light)" },
darkMode: {
"@media":
"(prefers-color-scheme: dark), (prefers-color-scheme: no-preference)",
},
hover: { selector: "&:hover" },
focus: { selector: "&:focus" },
},
defaultCondition: false,
properties: {
background: withBlackAndWhite,
color: withBlackAndWhite,
borderColor: withBlackAndWhite,
},
});
export const atoms = createAtomsFn(layoutStyles, colorStyles);
When I generate the css, vanilla-extract generate all classes to all possible colors in background, color and borderColor with all possible conditions
I think in a production scenario, devs will only create classes to brand related colors, but even though, can be very useful with we can purge some unused rules
(Sorry about the english)
Hi, thanks for creating this library! I was eager to try it with Nextjs, but faced some issues. I'm using Nextjs v 10.0.7 and latest vanilla-extract. I have this setup:
next.config.js:
const { VanillaExtractPlugin } = require('@vanilla-extract/webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
config.plugins.push(new VanillaExtractPlugin({
// allowRuntime: true
}));
config.plugins.push(new MiniCssExtractPlugin())
return config;
},
};
.babelrc:
{
"presets": ["next/babel"],
"plugins": [
"@vanilla-extract/babel-plugin"
]
}
When I try to run yarn dev
, I get:
Error: Cannot find module 'webpack/lib/NormalModule'
Require stack:
- /{projectpath}/node_modules/mini-css-extract-plugin/dist/index.js
- /{projectpath}/node_modules/mini-css-extract-plugin/dist/cjs.js
- /{projectpath}/next.config.js
Do you perhaps an idea how to solve this: Thanks!
I just went ahead to migrate our 61 .treat.js
files in our project to vanilla-extract and it all went really smoothly. Good job for making the migration so painless!
Of course we're using none of the css variables feature yet, but the nice thing is that we can now progressively migrate it piece by piece
One thing that broke was this though:
import stepBgImg from "./imgs/steps-bg.svg";
const container = style({
backgroundImage: `url("${stepBgImg}")`
})
it showed a rather long and unreadable error message before realising that vanilla-extract is probably more clever than I've expected. So I tried doing
const container = style({
backgroundImage: `url('./imgs/steps-bg.svg')`,
})
which worked!
So maybe this is worth mentioning in the migration guide?
Cheers!
Hi vanilla team,
Thank you for your great job on this project. However, I find out that there is on proper way for my framework to use this project.
I have several packages managed in a monorepo, and I use tsc
to compile them. Their dependency relations are managed by tsc's project reference feature. If I switch to vite or esbuild, I'll have to manage it myself and I think it's a waste of the ability of typescript. BTW, here is my monorepo: https://github.com/Saul-Mirone/milkdown.
So I suggest that maybe you can add a feature, when package Foo is using vanilla-extract
, it just compile it as typescript, and for users import this package Foo, they need to configure vanilla-extract themselves to get styles in Foo works.
Hi, Thanks for great library π
I am having following error after installed mini-css-extract-plugin.
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
Error: Cannot find module 'webpack/lib/util/identifier'
Require stack:
- /node_modules/mini-css-extract-plugin/dist/index.js
- /node_modules/mini-css-extract-plugin/dist/cjs.js
- /next.config.js
- /node_modules/next/dist/server/config.js
- /node_modules/next/dist/server/next.js
- /node_modules/next/dist/server/lib/start-server.js
- /node_modules/next/dist/cli/next-dev.js
- /node_modules/next/dist/bin/next
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15)
at Function.mod._resolveFilename (//node_modules/next/dist/build/webpack/require-hook.js:96:28)
at Function.Module._load (internal/modules/cjs/loader.js:725:27)
at Module.require (internal/modules/cjs/loader.js:952:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.<anonymous> (//node_modules/mini-css-extract-plugin/dist/index.js:10:19)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'/node_modules/mini-css-extract-plugin/dist/index.js',
'/node_modules/mini-css-extract-plugin/dist/cjs.js',
'/next.config.js',
'/node_modules/next/dist/server/config.js',
'/node_modules/next/dist/server/next.js',
'/node_modules/next/dist/server/lib/start-server.js',
'/node_modules/next/dist/cli/next-dev.js',
'/node_modules/next/dist/bin/next'
]
}
next.config.js
const { VanillaExtractPlugin } = require('@vanilla-extract/webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
plugins: [
new VanillaExtractPlugin(),
new MiniCssExtractPlugin()
],
module: {
rules: [
{
test: /\.vanilla\.css$/i, // Targets only CSS files generated by vanilla-extract
use: [
MiniCssExtractPlugin.loader,
{
loader: require.resolve('css-loader'),
options: {
url: false // Required as image imports should be handled via JS/TS import statements
}
}
]
}
]
}
};
.babelrc
{
"presets": ["next/babel"],
"plugins": ["@vanilla-extract/babel-plugin"]
}
Currently, there is no any (compile-time or emit-time) checking of selector string correctness. Latest typescript can check it with template string types, but maybe it's better to create (or use existing, if any) some util to form selector string? And certainly string should be checked when css emitted.
Hey there, I'm having trouble getting globalStyle
to apply the correct theme. I have the theme being applied to my html
element but the --var
s are being called from the first available theme className in the extracts file rather than the currently applied one.
Eg. --palette-background-default__1tdsuw195
is being applied while the theme has --palette-background-default__196i551195
available.
Omitting as any
in the following example results in a type error. Also cannot set them as numbers inside createGlobalTheme
.
export const vars = createGlobalTheme(":root", {
fontFamily: {
title: "'Lato', sans-serif",
body: "'Raleway', sans-serif",
},
fontWeight: {
title: "700",
body: "400",
},
});
globalStyle("html, body", {
fontFamily: vars.fontFamily.body,
fontWeight: vars.fontWeight.body as any,
});
I would love to experiment with this tool as the main way to get css into my LitElement web comps, but we donβt use and bundlers at all currently and Iβd rather not introduce one just for a build step.
Is there an example of generating the css files without a bundler plugin? Say with just a regular node js script?
Using globalStyle()
based on a parentClass created from style()
is fine...
export const parentClass = style({});
globalStyle(`${parentClass} > a`, {
color: 'pink'
});
...but if parentClass is created using composeStyles()
(or atoms()
?) then it can no longer work with globalStyle()
as it is no longer just a single class name.
Obvious I guess but I stumbled on this when I changed a parent class from style()
to composeStyles()
and the related globalStyles()
stopped getting applied.
(If you're curious about why we were using globalStyle()
it was for applying some table tr
and td
styles based on an overall table class and we didn't want to add lots of specific class names on those elements)
A common pattern when using React 'primitive' libraries such as radix or reach-ui is to allow styling the component on a given state targetting an attribute and it's value, example:
[data-reach-combobox] {
}
/* root element in a specific state */
/* possible states: "idle" | "suggesting" | "navigating" | "interacting" */
[data-reach-combobox][data-state="STATE_REF"] {
}
Using vanilla extract, targetting attributes works just fine but a specific value results in an Error: Invalid selector: '&[data-state]="on"'
:
export const panel = style({
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
borderWidth: '1px',
selectors: {
'&[data-state]="on"': {
//this throws an error
},
'&[data-state]': {
//this works fine
},
},
})
I think this does it:
https://codesandbox.io/s/kind-brook-sl451?file=/src/App.css.ts:505-569
Output of npx envinfo --system --npmPackages @vanilla-extract/css,@vanilla-extract/webpack-plugin,@vanilla-extract/esbuild-plugin,@vanilla-extract/vite-plugin,@vanilla-extract/sprinkles,webpack,esbuild,vite --binaries --browsers
:
System:
OS: Linux 5.4 Linux Mint 20.2 (Uma)
CPU: (16) x64 AMD Ryzen 7 3700X 8-Core Processor
Memory: 9.54 GB / 31.33 GB
Container: Yes
Shell: 5.0.17 - /bin/bash
Binaries:
Node: 12.19.0 - ~/.config/nvm/12.19.0/bin/node
Yarn: 1.22.5 - /usr/bin/yarn
npm: 7.11.1 - ~/.config/nvm/12.19.0/bin/npm
Browsers:
Chrome: 92.0.4515.131
Firefox: 90.0.2
npmPackages:
@vanilla-extract/css: ^1.2.1 => 1.2.1
@vanilla-extract/sprinkles: ^1.0.0 => 1.0.0
@vanilla-extract/webpack-plugin: ^1.1.0 => 1.1.0
Originally posted by minht11 June 20, 2021
Could support be added for :is
selector, so use case like this would work:
style({
background: 'red',
selectors: {
'&:is(:focus-within, :hover)': {
background: 'blue',
}
}
})
There probably would be some restrictions to it, but since :is
selector references element itself it shouldn't be too much of a problem.
You can use globalStyle
as an alternative right now, but it doesn't feel as clean.
Hello, first thanks for the great library!
In examples, I see this:
export const vars = createThemeContract({
color: {
brand: null
},
font: {
body: null
}
});
but NullableTokens are defined like this:
export type NullableTokens = {
[key: string]: string | Tokens | null;
};
So in TypeScript strict mode, example is failing on a wrong typing.
Should it be rather defined like this
export type NullableTokens = {
[key: string]: string | NullableTokens | null;
};
Or am I missing something?
I can create PR for it, but maybe I'm just misunderstanding it. (I've only been playing with this lib for a few days).
Wrong type for
export declare function createThemeContract<ThemeContract extends Contract>(themeContract: ThemeContract): ThemeVars<ThemeContract>;
GIves error:
Argument of type 'Tokens' is not assignable to parameter of type 'MapLeafNodes<MapLeafNodes<Tokens, CSSVarFunction>, CSSVarFunction>'.
Types of property 'hey' are incompatible.
Type 'string' is not assignable to type 'CSSVarFunction'.ts(2345)
import { createGlobalTheme, createThemeContract } from '@vanilla-extract/css';
type Tokens = {
hey: string;
};
const defaultTokens: Tokens = {
hey: '',
};
export const vars = createThemeContract<Tokens>(defaultTokens);
createGlobalTheme(':root', vars, defaultTokens);
Output of npx envinfo --system --npmPackages @vanilla-extract/css,@vanilla-extract/webpack-plugin,@vanilla-extract/esbuild-plugin,@vanilla-extract/vite-plugin,@vanilla-extract/sprinkles,webpack,esbuild,vite --binaries --browsers
:
System:
OS: macOS 11.4
CPU: (8) arm64 Apple M1
Memory: 88.81 MB / 16.00 GB
Shell: 3.2.57 - /bin/bash
Binaries:
Node: 16.4.1 - ~/.nvm/versions/node/v16.4.1/bin/node
Yarn: 1.22.10 - /opt/homebrew/bin/yarn
npm: 7.18.1 - ~/.nvm/versions/node/v16.4.1/bin/npm
Browsers:
Brave Browser: 91.1.25.68
Chrome: 91.0.4472.114
Safari: 14.1.1
npmPackages:
@vanilla-extract/css: ^1.1.0 => 1.1.0
@vanilla-extract/webpack-plugin: ^1.0.1 => 1.0.1
webpack: ^5.24.2 => 5.43.0
Hello,
The lib looks awesome, but I've one question given that the library uses CSS Variables : is the library compatible with IE 11 ?
Thanks
Is there a way to do automatic prefixing available for vanilla-extract? I'm styling a slider and the number of prefixes needed to get any sort of consistency across browsers is painful. If there is a plugin or addon available or it's already implemented and simply not documented or I missed the place where it's explained, please point me to it (I use Vite if that's relevant). Otherwise, it's a feature I would love to see.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. πππ
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google β€οΈ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.