Git Product home page Git Product logo

vite-plugin-stylex's Introduction

vite-plugin-stylex

Warning

This is an unofficial repo. This plugin is dedicated to providing stable stylex integration.

Features

  • CSS automatic injection
  • Support HMR
  • Control css order by manually
  • Support Vite-based SSR framework

Usage

$ yarn add vite-plugin-stylex-dev -D
// vite.config.ts
import { defineConfig } from 'vite'
import { stylex } from 'vite-plugin-stylex-dev'

export default defineConfig({
  plugins: [stylex()]
})

// then find your project entry(If you don't using manuallyControlCssOrder option)
import 'virtual:stylex.css'

Options

params type default description
include string | RegExp | Array<string | RegExp> /\.(mjs|js|ts|vue|jsx|tsx)(\?.*|)$/ Include all assets matching any of these conditions.
exclude string | RegExp | Array<string | RegExp> - Exclude all assets matching any of these conditions.
importSources string[] ['stylex', '@stylexjs/stylex'] See stylex document.
babelConfig object {} Babel config for stylex
unstable_moduleResolution Record<string,any> { type: 'commonJS', rootDir: process.cwd() } See stylex document
useCSSLayers boolean false See stylex document
optimizedDeps Array<string> [] Work with external stylex files or libraries
manuallyControlCssOrder boolean |object false control css order by manually
enableStylexExtend boolean | StylexExtendOptions false see @stylex-extend/babel-plugin docss

Q & A

Q&A

Author

Kanno

LICENSE

MIT

vite-plugin-stylex's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

vite-plugin-stylex's Issues

Version: 0.8.1

Background

HMR

Split dev server as three phase. Is the scanning transform schedule. At scanning stage we collect should be processed file. At transform stage we pipe us file with styleX compiler. Then the schedule will
handle the result to do incremental HMR.

Adapter

It's a planning to provide separate HMR integration for the React framework.

TODO

RSD :)

CheckList

  • fix HMR
  • support incremental HMR
  • RSD...

In v0.8.1 us plugin support incremental HMR. And other improve is remove noisy HMR tips.

npm run dev not working

Everything seems to be working when I run the build, but not when I npm run dev in my app.

My app is importing a component library that I have created. This library is using StyleX. It does not compile StyleX into the build though. The vite.config in the component library has this in the plugins section

...(command !== 'build' ? [stylexPlugin()] : []), // Only include stylexPlugin when not building

I thought I would not want to compile the component library, and rather the user of it would need to have stylex installed and they would compile.

As I said, works when running the build. Not when running npm run dev

Cannot use variables

[vite] Internal server error: /home/aspizu/Documents/Projects/stylex-components/src/Base.tsx: Only static values are allowed inside of a stylex.create() call.
  Plugin: vite-plugin-stylex
import react from "@vitejs/plugin-react"
import {defineConfig} from "vite"
import {stylexPlugin} from "vite-plugin-stylex-dev"

export default defineConfig({
    plugins: [
        react(),
        stylexPlugin({
            unstable_moduleResolution: {
                type: "commonJS",
                rootDir: "/src",
            },
        }),
    ],
    build: {
        target: "esnext",
    },
})
import {colors, fontFamily} from "./tokens.stylex.ts"
import * as stylex from "@stylexjs/stylex"

export const fontFamily = stylex.defineVars({
    sans: "Inter",
    serif: "Merriweather",
    mono: "Cascadia Code",
})

export const colors = stylex.defineVars({
    background: "#000000",
    foreground: "#ffffff",
})

LightningCSS @custom-media does not work

Stackblitz (https://stackblitz.com/edit/remix-run-remix-bgjqjp?file=app%2Fstyles%2Findex.css)

@custom-media does not work either in dev mode nor production build.

Steps to reproduce:

  1. Uncomment @media (--mx-1) condtion in styles:

/routes/_index.tsx:

const styles = stylex.create({  
  x: {
    color: {
      default: 'gray',
      // '@media (width < 1024px)': 'blue',
      '@media (--mx-1)': 'blue',
    },
  },
});

Output log:

12:48:34 PM [vite] Internal server error: Custom media query --mx-1 is not defined
  Plugin: vite:css
  File: vite-plugin:stylex.css:4:1
  2  |  .x1p7i66b{font-family:system-ui,sans-serif}
  3  |  .xwxc2jc{line-height:1.8}
  4  |  @media (--mx-1){.x19mpqw0.x19mpqw0{color:blue}}
     |   ^

Note that the custom css file included in root.tsx processes @custom-media as expected:

/styles/index.css:

@import './reset.css';

@custom-media --mx-1 (width <= 1024px);

.primary {
  // ...
  
  @media (--mx-1) {
    color: blue;
  }
}

So the problem may be related to the wrong order of importing the styles, e.g. stylex build css simply ignores the @custom-media described in the imported /styles/index.css.

I also added an example of how manual css import using ?url can be handled in remix (so we handle import order from user perspective), but this plugin does not support this feature for manual stylex css import. (addressed in this issue #11).

import { LinksFunction } from '@remix-run/node';

import $styles from '~/styles/index.css?url';

export const links: LinksFunction = () => [
	// Preload CSS as a resource to avoid render blocking
	// avoid HMR issues in dev mode
	...(!import.meta.env.DEV ? [{ rel: 'preload', href: $styles, as: 'style' }] : []),

	// These should match the css preloads above to avoid css as render blocking resource
	{ rel: 'stylesheet', href: $styles },
];

The example using custom import from similar package vite-plugin-stylex:

/styles/index.css:

@import './core/custom-media.css';
@import './core/reset.css' layer(core);
@import './core/fonts.css' layer(core);

@stylex stylesheet;

Preload styles via <link rel="stylesheet" />

With Vite's future support for .css?url imports, will it be possible to enable manual preloading for styles? For example, using Remix:

export const links = () => [
	// Preload CSS as a resource to avoid render blocking
	{ rel: 'preload', href: stylesHref, as: 'style' },

	// These should match the css preloads above to avoid css as render blocking resource
	{ rel: 'stylesheet', href: stylesHref },
];

Style declaration including only `null` values result in errors being thrown

The problem
Style objects that include only entries with null values result in stylex.create should never be called. It should be compiled away. exception.

How to reproduce
Steps to reproduce:

  1. Create a React + TypeScript project with StyleX
  2. Create a style block/declaration including only null values, f.ex:
const styles = stylex.create({
  test: {
    padding: null,
  }
});
  1. Apply to any node in a given component

Code Sandbox example (expand console in the browser window - might need a reload to show up)

Plan: 0.8.0

CheckList

  • Bump @stylex-extend/babel-plugin and @stylex-extend/babel-plugin deps version.
  • Add new option adapter for future feature.
  • Re-implement hmr logic.
  • Updated document description.

Background

This version will cause breaking. Now we don't apply virtual tag for each module. User should define the virtual module entry by manually(If you don't using manuallyControlCssOrder). Like

// your entry file

import 'virtual:stylex.css'

Unnecessary duplicate assets included in the build when using `?url` style imports

Stackblitz

Using side-effect import everything works properly, resulting in single css file:

import './styles/index.css'

Logs:

❯ pnpm build

> remix-demo@ build /home/predaytor/remix-stylex
> remix vite:build

vite v5.2.8 building for production...
✓ 84 modules transformed.
build/client/.vite/manifest.json                1.38 kB │ gzip:  0.41 kB
build/client/assets/root-CfhkM_gF.css           0.60 kB │ gzip:  0.32 kB
build/client/assets/root-D1dZ27zj.js            1.39 kB │ gzip:  0.81 kB
build/client/assets/_index-D5VKFgXt.js          2.03 kB │ gzip:  1.14 kB
build/client/assets/jsx-runtime-BlSqMCxk.js     8.09 kB │ gzip:  3.05 kB
build/client/assets/entry.client-DRdY3GlJ.js   14.06 kB │ gzip:  5.01 kB
build/client/assets/components-Wh-oPew1.js    212.85 kB │ gzip: 68.83 kB
✓ built in 1.55s
vite v5.2.8 building SSR bundle for production...
"create" is imported from external module "@stylexjs/stylex" but never used in "app/theme.stylex.ts", "app/Card.tsx" and "app/routes/_index.tsx".
✓ 8 modules transformed.
build/server/.vite/manifest.json               0.22 kB
build/server/assets/server-build-CfhkM_gF.css  0.60 kB
build/server/index.js                          6.99 kB
✓ built in 90ms

/build/client/assets/root-CfhkM_gF.css:

@layer core {
	* {
		box-sizing: border-box;
	}
}
:root {
	--x: pink;
	--x1yjbm8s: #000;
}
.x1tamke2:not(#\#) {
	padding: 16px;
}
.xur7f20:not(#\#):not(#\#) {
	border-radius: 8px;
}
.x12peec7:not(#\#):not(#\#):not(#\#) {
	background-color: #fff;
}
.x1ik0xcp:not(#\#):not(#\#):not(#\#) {
	box-shadow: 0 0 16px #0000001a;
}
.x3ja3p5:not(#\#):not(#\#):not(#\#) {
	color: #329b25;
}
.x1wzkho:not(#\#):not(#\#):not(#\#) {
	color: #ff6850;
	color: color(display-p3 1.04321 0.334712 0.217808);
	color: lch(64.2906% 106.837 40.8577);
}
.x195j60l:not(#\#):not(#\#):not(#\#) {
	color: var(--x1yjbm8s);
}
@media (max-width: 1024px) {
	.x1yewo9u.x1yewo9u:not(#\#):not(#\#):not(#\#) {
		color: purple;
	}
}

Using manual ?url import results with separate index-ClnSbR9a.css file with the preload link included, which comes from root.tsx, the content of which already is present in root-CfhkM_gF.css. I believe the expected behavior should be similar to side-effect import, including and preloading a single css file (in this case it should be root-CfhkM_gF.css):

import $styles from '~/styles/index.css?url';

export const links: LinksFunction = () => [
	// Preload CSS as a resource to avoid render blocking
	{ rel: 'preload', href: $styles, as: 'style' },

	// These should match the css preloads above to avoid css as render blocking resource
	{ rel: 'stylesheet', href: $styles },
];

Devtools:

<!-- ... -->
<link rel="stylesheet" href="/assets/root-CfhkM_gF.css" />
<link rel="preload" href="/assets/index-ClnSbR9a.css" as="style" />
<link rel="stylesheet" href="/assets/index-ClnSbR9a.css" />

Logs:

❯ pnpm build

> remix-demo@ build /home/predaytor/remix-stylex
> remix vite:build

vite v5.2.8 building for production...
✓ 85 modules transformed.
build/client/.vite/manifest.json                1.55 kB │ gzip:  0.45 kB
build/client/assets/index-ClnSbR9a.css          0.07 kB │ gzip:  0.08 kB
build/client/assets/root-CfhkM_gF.css           0.60 kB │ gzip:  0.32 kB
build/client/assets/root-CBQOkiJk.js            1.51 kB │ gzip:  0.89 kB
build/client/assets/_index-D5VKFgXt.js          2.03 kB │ gzip:  1.14 kB
build/client/assets/jsx-runtime-BlSqMCxk.js     8.09 kB │ gzip:  3.05 kB
build/client/assets/entry.client-DRdY3GlJ.js   14.06 kB │ gzip:  5.01 kB
build/client/assets/components-Wh-oPew1.js    212.85 kB │ gzip: 68.83 kB
✓ built in 1.77s
vite v5.2.8 building SSR bundle for production...
"create" is imported from external module "@stylexjs/stylex" but never used in "app/theme.stylex.ts", "app/Card.tsx" and "app/routes/_index.tsx".
✓ 9 modules transformed.
build/server/.vite/manifest.json               0.38 kB
build/server/assets/index-ClnSbR9a.css         0.07 kB
build/server/assets/server-build-CfhkM_gF.css  0.60 kB
build/server/index.js                          7.30 kB
✓ built in 137ms

/build/client/assets/index-ClnSbR9a.css:

@layer core {
	* {
		box-sizing: border-box;
	}
}
:root {
	--x: pink;
}
@stylex-dev;

/build/client/assets/root-CfhkM_gF.css:

@layer core {
	* {
		box-sizing: border-box;
	}
}
:root {
	--x: pink;
	--x1yjbm8s: #000;
}
.x1tamke2:not(#\#) {
	padding: 16px;
}
.xur7f20:not(#\#):not(#\#) {
	border-radius: 8px;
}
.x12peec7:not(#\#):not(#\#):not(#\#) {
	background-color: #fff;
}
.x1ik0xcp:not(#\#):not(#\#):not(#\#) {
	box-shadow: 0 0 16px #0000001a;
}
.x3ja3p5:not(#\#):not(#\#):not(#\#) {
	color: #329b25;
}
.x1wzkho:not(#\#):not(#\#):not(#\#) {
	color: #ff6850;
	color: color(display-p3 1.04321 0.334712 0.217808);
	color: lch(64.2906% 106.837 40.8577);
}
.x195j60l:not(#\#):not(#\#):not(#\#) {
	color: var(--x1yjbm8s);
}
@media (max-width: 1024px) {
	.x1yewo9u.x1yewo9u:not(#\#):not(#\#):not(#\#) {
		color: purple;
	}
}

I think it's the last issue I found yet, thx for resolving!

Vite: css hmr is not supported in runtime mode.

Not to say it's a plugin issue, but when using the css ?url imports, after updating the styles, the browser window refreshes, losing its previous state, e.g. HMR is not working properly.

I can't reproduce it with the given remix example, everything works perfectly here except I removed the now deprecated <LiveReload /> and solved the hmr issue in dev mode when using the style preload:

export const links: LinksFunction = () => [	
  ...(!import.meta.env.DEV ? [{ rel: 'preload', href: stylesHref, as: 'style' }] : []),
  // ...
]

It's most likely not related to vite-stylex-plugin-dev, which is hard to reproduce at the moment, as I'm using a custom vite dev server with the Hono Framework for Remix, but I'm curious what you think could be causing this? Didn't find much info on it.

On every style update (not regular jsx mods) this comes out:

9:15:31 PM [vite] hmr update /app/root.tsx
9:15:31 PM [vite] hmr update /app/styles/index.css?direct
[vite] css hmr is not supported in runtime mode.

This line comes from packages/vite/src/runtime/hmrHandler.ts:

export async function handleHMRPayload(runtime: ViteRuntime, payload: HMRPayload): Promise<void> {
    const hmrClient = runtime.hmrClient;
    if (!hmrClient || runtime.isDestroyed()) return;

    switch (payload.type) {
        // ...

        case 'update':
            await hmrClient.notifyListeners('vite:beforeUpdate', payload);
            await Promise.all(
                payload.updates.map(async (update): Promise<void> => {
                    if (update.type === 'js-update') {
                        // runtime always caches modules by their full path without /@id/ prefix
                        update.acceptedPath = unwrapId(update.acceptedPath);
                        update.path = unwrapId(update.path);
                        return hmrClient.queueUpdate(update);
                    }

                    hmrClient.logger.error('[vite] css hmr is not supported in runtime mode.');
                }),
            );
            await hmrClient.notifyListeners('vite:afterUpdate', payload);
            break;
    }
}

[IMPROVE]: Refactor plugin logic and add new features

TL;DR

Background

Although plugin can work well for most scenes. But from the code isn't a good practice for design. So i want to change it.

Proposal

  • Split current logic for dev and prod.
  • Split the logic for ssr and csr.
  • Integrated @stylex-extend/babel-plugin.
  • Provide rollup adapter.

Improve Caching

I noticed that when I restart my app none of the styles have been loaded/generated. Every time I restart the app I see the whole app unstyled.

I was talking with @nmn and he said that stylex relies heavily on caching. To me it seems like there is something that could be improved here.

Here is me restarting the dev server and all the styles getting blown away

CleanShot.2024-06-19.at.11.01.29.mp4

Here is an example of styles flashing on refresh

CleanShot.2024-06-19.at.11.02.08.mp4

Inconsistent bundling of css assets between builds (Remix)

When using the ?url import, there seems to be a mismatch between the generated assets, resulting in two identical css files (with different hashes), with the mismatched included at the top of the <head/>. I think it started after the switch to Rollup bundler in some of the earlier releases.

For some reason I cannot reproduce bug in the sandbox, I think it has to do with remix bundler. If you can point out where this is related, I could open the issue in the remix repo. With the remix example provided from this repo all is fine.

This happens occasionally between builds, so maybe it's due to some internal caching. When this mismatch occurs, this line outputs:

✓ 1 resource moved from Remix server build to client resources.
build/client/assets/index-CiOyfy0p.css

Logs:

> remix vite:build

Using vars defined in .dev.vars
Using vars defined in .dev.vars
Using vars defined in .dev.vars
Using vars defined in .dev.vars
vite v5.2.11 building for production...
✓ 827 modules transformed.
Generated an empty chunk: "phone-textfield".
build/client/.vite/manifest.json                            18.13 kB │ gzip:  1.81 kB
build/client/assets/sprite-BdV8AqDD.svg                     30.02 kB │ gzip:  9.43 kB
build/client/assets/index-N3JczSMr.css                     102.92 kB │ gzip: 21.23 kB
build/client/assets/phone-textfield-l0sNRNKZ.js              0.00 kB │ gzip:  0.02 kB
build/client/assets/_app.users.teachers-D0KjJBcV.js          0.13 kB │ gzip:  0.14 kB
build/client/assets/_app.users.removed-Bw8pfhzk.js           0.13 kB │ gzip:  0.14 kB
build/client/assets/_app.users.administrators-zltEt6Gl.js    0.13 kB │ gzip:  0.14 kB
build/client/assets/_app.users.applicants-zltEt6Gl.js        0.13 kB │ gzip:  0.14 kB
build/client/assets/recovery-DNcuDyGd.js                     0.13 kB │ gzip:  0.14 kB
build/client/assets/toggle-button-BRlrV58r.js                0.29 kB │ gzip:  0.23 kB
build/client/assets/data-RBlXXuFm.js                         0.36 kB │ gzip:  0.31 kB
build/client/assets/_app.groups-DRAlv3Dh.js                  0.37 kB │ gzip:  0.29 kB
build/client/assets/_app.applications-DSix6XLc.js            0.37 kB │ gzip:  0.29 kB
build/client/assets/_app.dashboard-DGrcCHYH.js               0.37 kB │ gzip:  0.29 kB
build/client/assets/_app.profile-CDyQESv2.js                 0.37 kB │ gzip:  0.29 kB
build/client/assets/_app.calendar-B-6OaHIp.js                0.37 kB │ gzip:  0.30 kB
build/client/assets/_app.learning-DN9SaJxK.js                0.37 kB │ gzip:  0.30 kB
build/client/assets/_app.report-DHEzYFMA.js                  0.37 kB │ gzip:  0.30 kB
build/client/assets/_app.library-BOJ6LJAi.js                 0.37 kB │ gzip:  0.30 kB
build/client/assets/_app.transactions-BwQdegkR.js            0.37 kB │ gzip:  0.30 kB
build/client/assets/_app.history-ocq8kroE.js                 0.37 kB │ gzip:  0.30 kB
build/client/assets/_app.settings-CeF1owLH.js                0.37 kB │ gzip:  0.31 kB
build/client/assets/_app.messages-S8M7tn2Y.js                0.37 kB │ gzip:  0.30 kB
build/client/assets/icon-button--aXbSP48.js                  0.41 kB │ gzip:  0.28 kB
build/client/assets/birthday-datefield-BqNzzUqC.js           0.42 kB │ gzip:  0.33 kB
build/client/assets/icon-D09kYBQN.js                         0.43 kB │ gzip:  0.30 kB
build/client/assets/heading-C_rbyHuK.js                      0.48 kB │ gzip:  0.34 kB
build/client/assets/header-C0nPIVLm.js                       0.65 kB │ gzip:  0.49 kB
build/client/assets/container-B01piXsx.js                    0.70 kB │ gzip:  0.42 kB
build/client/assets/logo-DuT4e1vb.js                         0.75 kB │ gzip:  0.49 kB
build/client/assets/phone-textfield-C-jSd1_r.js              1.00 kB │ gzip:  0.59 kB
build/client/assets/email-textfield-CTVomzYq.js              1.42 kB │ gzip:  0.77 kB
build/client/assets/_app.users_.students._id-B3Yrzq6t.js     1.82 kB │ gzip:  0.95 kB
build/client/assets/_auth.signup-CArL0x5s.js                 2.52 kB │ gzip:  1.18 kB
build/client/assets/_auth-DBv4tsY3.js                        2.77 kB │ gzip:  1.44 kB
build/client/assets/_auth.login-ChIY2W4h.js                  2.84 kB │ gzip:  1.37 kB
build/client/assets/stylex-BOjyk742.js                       2.95 kB │ gzip:  1.35 kB
build/client/assets/route-D9NRnaPk.js                        2.99 kB │ gzip:  1.23 kB
build/client/assets/_app.users_.students.new-DLn0FcZR.js     3.25 kB │ gzip:  1.65 kB
build/client/assets/root-Csrl-H1Q.js                         3.39 kB │ gzip:  1.54 kB
build/client/assets/avatar-CWYAx4KT.js                       3.42 kB │ gzip:  1.40 kB
build/client/assets/form-C70NaR-f.js                         3.98 kB │ gzip:  1.55 kB
build/client/assets/checkbox-CoohEvgQ.js                     4.08 kB │ gzip:  1.33 kB
build/client/assets/route-j0DL5Qgm.js                        4.56 kB │ gzip:  2.21 kB
build/client/assets/input-qekBshbH.js                        6.82 kB │ gzip:  2.00 kB
build/client/assets/password-textfield-Qbj1_dUL.js           8.38 kB │ gzip:  2.30 kB
build/client/assets/jsx-runtime-C7dT0ItP.js                  9.95 kB │ gzip:  3.63 kB
build/client/assets/entry.client-VFfHxz5W.js                11.63 kB │ gzip:  4.09 kB
build/client/assets/route-COXK8fsl.js                       21.87 kB │ gzip:  6.73 kB
build/client/assets/index-CQFX0XzH.js                       36.81 kB │ gzip: 11.07 kB
build/client/assets/components-DxQqOcDi.js                 276.88 kB │ gzip: 87.94 kB
build/client/assets/sprite-D7EuGFbZ.js                     329.70 kB │ gzip: 91.42 kB
✓ built in 2.62s
Using vars defined in .dev.vars
Using vars defined in .dev.vars
vite v5.2.11 building SSR bundle for production...
"chain" is imported from external module "react-aria" but never used in "app/routes/_app.users.students/data.tsx", "app/components/fieldgroup.tsx", "app/components/link.tsx", "app/components/upload-file-field.tsx", "app/components/searchfield.tsx", "app/routes/_app/route.tsx", "app/components/avatar/avatar.tsx", "app/routes/_app.users/user-alert-dialog.tsx" and "app/routes/_app.users.students/route.tsx".
✓ 100 modules transformed.
build/server/.vite/manifest.json           0.51 kB
build/server/assets/sprite-BdV8AqDD.svg   30.02 kB
build/server/assets/index-CiOyfy0p.css   102.92 kB
build/server/index.js                    204.82 kB

✓ 1 asset moved from Remix server build to client assets.
build/client/assets/index-CiOyfy0p.css

✓ built in 862ms

Знімок екрана 2024-05-16 о 11 37 54 Знімок екрана 2024-05-16 о 11 40 38

Uncaught TypeError: can't access property "__k", t2 is null

Uncaught TypeError: can't access property "__k", t2 is null
import civet from "@danielx/civet/dist/vite.mjs";
import preact from "@preact/preset-vite";
import { stylexPlugin } from "vite-plugin-stylex-dev";
import { defineConfig } from "vite";

export default defineConfig({
  plugins: [preact(), civet({ implicitExtension: false }), stylexPlugin()],
});

Histoire unable to build when using Nuxt + Stylex

Here's the minimal reproduction of the stack I'm working with: https://stackblitz.com/edit/histoire-vue3-starter-83xt5n?file=package.json

When running npm run story:build this is the error message I get:

Error while collecting story /home/projects/histoire-vue3-starter/src/BaseButton.story.vue:
_0x35fdff@https://histoirevue3starter-orgg.w-corp-staticblitz.com/blitz.41692973.js:40:1446727
throwClosedServerError@file:///home/projects/histoire-vue3-starter/node_modules/@nuxt/vite-builder/node_modules/vite/dist/node/chunks/dep-D8YhmIY-.js:49396:15
resolveId@file:///home/projects/histoire-vue3-starter/node_modules/@nuxt/vite-builder/node_modules/vite/dist/node/chunks/dep-D8YhmIY-.js:49550:33
resolve@file:///home/projects/histoire-vue3-starter/node_modules/@nuxt/vite-builder/node_modules/vite/dist/node/chunks/dep-D8YhmIY-.js:49717:37
rewriteImportStmts@file:///home/projects/histoire-vue3-starter/node_modules/vite-plugin-stylex-dev/dist/index.js#cjs:396:83
transform@file:///home/projects/histoire-vue3-starter/node_modules/vite-plugin-stylex-dev/dist/index.js#cjs:755:22
stylexServer/<@file:///home/projects/histoire-vue3-starter/node_modules/vite-plugin-stylex-dev/dist/index.js#cjs:204:29
handler@file:///home/projects/histoire-vue3-starter/node_modules/vite-plugin-stylex-dev/dist/index.js#cjs:30:14
stylexServer/<@file:///home/projects/histoire-vue3-starter/node_modules/vite-plugin-stylex-dev/dist/index.js#cjs:204:29
handler@file:///home/projects/histoire-vue3-starter/node_modules/vite-plugin-stylex-dev/dist/index.js#cjs:30:14
transform@file:///home/projects/histoire-vue3-starter/node_modules/vite/dist/node/chunks/dep-bb8a8339.js:44404:62

While running npm run story:dev, things work fine (probably because there's no such thing as a "closed server" in this mode).

Now I'm not sure if this is more of a Nuxt issue, as a plain Vite setup didn't throw this error either.
However I did get this Vite plugin to work for Histoire's build by commenting out code = await c.rewriteImportStmts(code, original); within

const plugin = {
        name: 'stylex',
        api: { ...
        async transform (code, id) { ... # from here

@stylex/open-props import (bug)

When importing the @stylexjs/open-props package im getting this error:

chunk-AEPY33DS.js?v=df81b0f4:401 Uncaught Error: stylex.defineVars should never be called. It should be compiled away.
    at stylexDefineVars (chunk-AEPY33DS.js?v=df81b0f4:401:13)
    at @stylexjs_open-props_lib_colors__stylex.js?v=e2f9464a:10:43
import * as stylex from "@stylexjs/stylex";
import { colors } from "@stylexjs/open-props/lib/colors.stylex";

const styles = stylex.create({
  base: {
    color: colors.blue11,
  },
});

function Button() {
  return <button {...stylex.props(styles.base)}>Click me!</button>;
}

export { Button };
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { stylexPlugin } from "vite-plugin-stylex-dev";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react(), stylexPlugin()],
});

[plugin:vite-plugin-stylex] C:\Users\Arun\Documents\GitHub\black\packages\frontend\src\components\buttons\Button.tsx: Only static values are allowed inside of a stylex.create() call.

Created tokens.stylex.ts as below.

import * as stylex from '@stylexjs/stylex';

const DARK = "@media (prefers-color-scheme: dark)";

export const colors = stylex.defineVars({ 
    primary: {default: '#fff', [DARK]: '#000'},
    primaryDark: {default: '#ccc', [DARK]: '#333'},
    bg: {default: '#fff', [DARK]: '#000'},
    white: {default: '#fff', [DARK]: '#000'},
    black: {default: '#000', [DARK]: '#fff'}
})

and Buttons.tsx as below

import * as stylex from '@stylexjs/stylex';
import { ComponentProps } from "react";
import { colors } from 'src/components/tokens.stylex';

type ButtonProps = {
    variant?: "primary",
    children?: React.ReactNode,
    styles?: stylex.StyleXStyles,
} & ComponentProps<"button">

const baseStyle = {
    borderWidth: '1px',
    borderStyle: 'solid',
    color: colors.white,
    borderRadius: '5px',
    cursor: 'pointer',
    padding: '10px 15px'
};

const s = stylex.create({
    base: baseStyle,
    primary: {
        borderColor: {
            default: colors.primary
        },
        color: {
            default: colors.black
        },
        backgroundColor: {
            default: colors.primary,
            ':hover': colors.primaryDark,
            ':focus': colors.primaryDark,
            ':active': colors.primaryDark,
        },
    }
});

const Button = ({ variant = "primary", styles, ...props }: ButtonProps) => (
    <button {...stylex.props(s.base, s[variant], styles)} {...props} />
);

export default Button;

I am getting the below error

[plugin:vite-plugin-stylex] C:\Users\Arun\Documents\GitHub\black\packages\frontend\src\components\buttons\Button.tsx: Only static values are allowed inside of a stylex.create() call.

Is it an existing issue? or kindly suggest a fix.

Issue on watch production build.

I'm working on a microfrontend project using vite-federation, and I need to rebuild every time to let the host gets the latest dist files. but when I use watchBuild, if I update the Stylex value, I encounter the following error: [vite-plugin-stylex] Could not load vite-plugin:stylex.css (imported by src/hdd/core/Spinner/BaseSpinner.tsx): rule is not iterable.

Below are my run scripts:

"scripts": {
  "build": "tsc && vite build",
  "preview": "vite preview --port 3001 --strictPort",
  "watchBuild": "concurrently \"pnpm build --watch\" \"pnpm wait-build && sleep 5 && pnpm preview\"",
  "wait-build": "wait-on dist/assets",
}

Could you advice on how to let the stylex can be rebuild on --watch? Thanks.

Bundle size increased and slow after upgrading to `0.8`

Cannot share a repro as it is a large private project, but heres a video:
https://youtu.be/BbROxmWa0CI

I use ~ alias everywhere to import my styles.

vite.config.ts

import { resolve, join } from 'path';
import { TanStackRouterVite } from '@tanstack/router-vite-plugin';
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';
import { stylex } from 'vite-plugin-stylex-dev';

// https://vitejs.dev/config/
export default defineConfig(async () => ({
  plugins: [
    react({
      babel: {
        plugins: ['relay'],
      },
    }),
    stylex({
      unstable_moduleResolution: {
        type: 'commonJS',
        rootDir: resolve(__dirname, 'src'),
      },
    }),
    TanStackRouterVite(),
  ],
  resolve: {
    alias: [
      {
        find: '~',
        replacement: join(resolve(__dirname), 'src'),
      },
    ],
  },

  // Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build`
  //
  // 1. prevent vite from obscuring rust errors
  clearScreen: false,
  // 2. tauri expects a fixed port, fail if that port is not available
  server: {
    port: 1420,
    strictPort: true,
    watch: {
      // 3. tell vite to ignore watching `src-tauri`
      ignored: ['**/src-tauri/**'],
    },
  },
}));

LightningCSS does not work in dev mode (HMR)

Stackblitz (https://stackblitz.com/edit/remix-run-remix-3gnvyb?file=app%2Froutes%2F_index.tsx)

Post-processing with LightningCSS does not work in dev mode on HMR updates. The production build works as expected.

const styles = stylex.create({
  x: {    
     color: 'lch(from pink calc(l + 10%) c h)',  
  },
});

css output:

color: lch(from pink calc(l + 10%) c h);

should be:

color: lch(from pink calc(l + 10%) c h);
color: lab(93.7873% 24.4367 3.75943);

Notice the defined CSS in the regular imported stylesheet (in our case the main import /styles/index.css), the post-processing is working properly.

[vite:css] Cannot read properties of null (reading 'moduleGraph')

After upgrade from 0.4.1 to 0.5.0/0.5.1 the vite build command now fails

I added manuallyControlCssOrder: true to vite config, that fixes the build (but breaks styling)

Error:

x Build failed in 290ms
error during build:
TypeError: [vite:css] Cannot read properties of null (reading 'moduleGraph')
file: vite-plugin:stylex.css
    at file:///Users/thomasvt/Developer/Workspace/adv-decision-support-fe/node_modules/vite-plugin-stylex-dev/dist/index.mjs:2:2377
    at a.transform (file:///Users/thomasvt/Developer/Workspace/adv-decision-support-fe/node_modules/vite-plugin-stylex-dev/dist/index.mjs:2:780)
    at async transform (file:///Users/thomasvt/Developer/Workspace/adv-decision-support-fe/node_modules/rollup/dist/es/shared/node-entry.js:18513:16)
    at async ModuleLoader.addModuleSource (file:///Users/thomasvt/Developer/Workspace/adv-decision-support-fe/node_modules/rollup/dist/es/shared/node-entry.js:18729:36)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.