(Vite) StyleX does not apply when run in production, but works on dev mode #1043
-
|
Environment: React 19, Stylex 0.11.1, vite-plugin-stylex 0.13.0, Vite 6.0.6 Issue: StyleX style templates are getting applied and work perfectly if I run my website in dev mode (npm run dev), but the styles do not apply at all in prod mode (npm run build, npm run preview) Tried methods:
package.json: I have a strong feeling that the flaw is in my project (maybe due to vite-plugin-stylex?), rather in stylex itself, that's why I'm asking for your insight in Discussions, rather than opening an Issue. |
Beta Was this translation helpful? Give feedback.
Replies: 7 comments 5 replies
-
|
I may be wrong, but this is my best debug idea for you. If you set it to false, and then dev no longer works, I would say that then you have an issue with your config files. I would also suggest moving to the PostCSS setup instead of the vite plugin. |
Beta Was this translation helpful? Give feedback.
-
|
Initial set up is one of the most painful parts of setting up any application. The good news is usually once your are done you won't have to touch it again for a long time. The maintainer here have acknowledged that they would like to make it less painful, but it's honestly just part of the game. here is a migration guide I made for my teams. It may be helpful, or I may be giving you a headache 😄 // Migrate from vite plugin to postCSS Migrating from Vite Plugin to PostCSS SetupThis guide will help you migrate your existing Vite application from using the StyleX Vite plugin to the new PostCSS-based setup. Overview of ChangesThe main changes in the new setup are:
Migration Steps1. Update DependenciesRemove the old StyleX Vite plugin and add the new required dependencies: # Remove old plugin
npm uninstall @stylexjs/vite-plugin
# Add new dependencies
npm install -D @stylexjs/[email protected] @stylexjs/[email protected] @babel/core @babel/preset-react @babel/preset-typescript autoprefixer postcss2. Create PostCSS ConfigurationCreate a new import path from "path";
import fs from "fs";
// This function helps detect the current environment/mode
function getEnvironmentMode() {
const nodeEnv = process.env.NODE_ENV;
return {
isDev: nodeEnv === "development",
isTest: nodeEnv === "test",
isProd: nodeEnv === "production",
};
}
// IMPORTANT: This function finds the path to open-props package
function getPackageIncludePaths(packageName) {
const projectRoot = process.cwd();
const nodeModulePaths = [path.join(projectRoot, "node_modules")];
let packagePath = null;
for (const nodeModulePath of nodeModulePaths) {
const packageJsonPath = path.resolve(
nodeModulePath,
packageName,
"package.json",
);
if (fs.existsSync(packageJsonPath)) {
packagePath = path.dirname(packageJsonPath);
break;
}
}
if (!packagePath) {
console.warn(`Could not find package ${packageName}`);
return [];
}
return [
path.join(packagePath, "**/*.{js,jsx,ts,tsx}"),
"!" + path.join(packagePath, "node_modules/**/*.{js,jsx,ts,tsx}"),
];
}
// Get the paths to open-props or node_modules packages you need to compile
// const openPropsIncludePaths = getPackageIncludePaths(
// "@open-props",
// );
export default {
plugins: {
"@stylexjs/postcss-plugin": {
include: [
"./src/**/*.{js,jsx,ts,tsx}",
// ...openPropsIncludePaths,
],
useCSSLayers: true,
fileName: "stylex.css",
outputCSS: true,
babelConfig: {
babelrc: false,
parserOpts: {
plugins: ["typescript", "jsx"],
},
plugins: [
[
"@stylexjs/babel-plugin",
{
dev: getEnvironmentMode().isDev,
test: getEnvironmentMode().isTest,
runtimeInjection: getEnvironmentMode().isDev,
genConditionalClasses: true,
treeshakeCompensation: true,
unstable_moduleResolution: {
type: "commonJS",
rootDir: path.resolve(),
},
},
],
],
},
},
autoprefixer: {},
},
};3. Update Vite ConfigurationModify your import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import path from "path";
export default defineConfig(({ mode }) => {
return {
plugins: [
react({
babel: {
plugins: [
[
"@stylexjs/babel-plugin",
{
dev: mode === "development",
test: mode === "test",
runtimeInjection: mode === "development",
genConditionalClasses: true,
treeshakeCompensation: true,
unstable_moduleResolution: {
type: "commonJS",
rootDir: path.resolve(),
},
},
],
],
},
}),
],
css: {
postcss: path.resolve(path.resolve(), "postcss.config.js"),
},
// optimizeDeps: {
// exclude: ["@open-props"],
// },
build: {
sourcemap: true,
target: "esnext",
},
};
});4. Update StyleX CSS FileCreate or update your @layer reset;
/* The @stylex directive is used by the StyleX PostCSS plugin.
* It will be replaced with generated CSS at build time.
*/
/* @stylex-injection-point */
@stylex;5. Update Entry PointsRemove any old StyleX imports and update your entry points: // src/main.tsx
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.tsx'
import './stylex.css' // Import the StyleX CSS file
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
</React.StrictMode>,
)TroubleshootingCommon Issues
Performance Optimization
Key Differences from Previous Setup
DependenciesMain Dependencies
Development Dependencies
|
Beta Was this translation helpful? Give feedback.
-
|
@PrivateN00b please share a reproduction of your setup if you want further help. The PostCSS setup should work in most Vite setups. |
Beta Was this translation helpful? Give feedback.
-
|
Thank you guys, all of you are amazing! If anyone else also faces this issue as I've had, then you will most likely find success by just following BMCwebdev's guide. I basically just copied it 1:1 and it worked. |
Beta Was this translation helpful? Give feedback.
-
|
@BMCwebdev we have an open issue to create a vite example in the StyleX repo, if you're interested in contributing your template to the codebase #888 |
Beta Was this translation helpful? Give feedback.
-
|
If all is working well, the setup shared by @BMCwebdev could be significantly simplified: babel.config.cjsmodule.exports = {
plugins: [
[
"@stylexjs/babel-plugin",
{
dev: process.env.NODE_ENV === "development",
test: process.env.NODE_ENV === "test",
runtimeInjection: process.env.NODE_ENV === "development",
genConditionalClasses: true,
treeshakeCompensation: true,
unstable_moduleResolution: {
type: "commonJS",
},
},
],
],
};
postcss.config.cjsmodule.exports = {
plugins: {
"@stylexjs/postcss-plugin": {
include: [
"./src/**/*.{js,jsx,ts,tsx}",
"./node_modules/my-library/**/*.{js,jsx,ts,tsx}",
"!./node_modules/my-library/node_modules/**/*.{js,jsx,ts,tsx}",
// Ideally you could just write "my-library", but not sure if that would currently work
],
useCSSLayers: true,
outputCSS: true,
fileName: "stylex.css",
},
autoprefixer: {},
},
};
vite.config.tsimport { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [
react(),
],
// optimizeDeps: {
// exclude: ["@open-props"],
// },
build: {
sourcemap: true,
target: "esnext",
},
});
Let me know if this worked for you guys. |
Beta Was this translation helpful? Give feedback.
-
|
Thanks @sergiocarneiro . I am trying to resolve some issues in updating one of my teams apps to the PostCSS config method right now actually and running into issues where the babel doesn't seem to be compiling and I keep running into the It is these node modules where I tend to always run into issues getting StyleX plugins configured correctly. Once I get this figured out I can figure out if I can make a template, but for now I cannot update my team's app to the new PostCSS method myself. |
Beta Was this translation helpful? Give feedback.
Initial set up is one of the most painful parts of setting up any application. The good news is usually once your are done you won't have to touch it again for a long time. The maintainer here have acknowledged that they would like to make it less painful, but it's honestly just part of the game.
here is a migration guide I made for my teams. It may be helpful, or I may be giving you a headache 😄
I tried to sanitize it for general use and not specifically for my use case. But every setup is different. I have no idea what version of React you are using for example.
If you are using AI tools like Cursor, try just feeding it this
Just hoping you can find some use in this.
// Migrate from vit…