Step-by-step guide on integrating StyleX into your fresh React project

As I delve into my new project, incorporating StyleX has proven to be a bit challenging especially when working with NextJS.

I find myself grappling with configuring the "next.config.js" file without causing conflicts with the existing "babel.config.js" file.

Despite scouring through the StyleX documentation, the solution still eludes me, making me question if I'm missing something obvious.

Current Setup:

.babelrc.js file:

module.exports = {
  presets: ["next/babel"],
  plugins: [
    [
      "@stylexjs/babel-plugin",
      {
        dev: process.env.NODE_ENV === "development",
        runtimeInjection: false,
        genConditionalClasses: true,
        treeshakeCompensation: true,
        unstable_moduleResolution: {
          type: "commonJS",
          rootDir: __dirname,
        },
      },
    ],
  ],
};

next.config.js file:

/** @type {import('next').NextConfig} */
const stylexPlugin = require("@stylexjs/nextjs-plugin");

const nextConfig = {
  reactStrictMode: true,
};

module.exports = stylexPlugin({
  rootDir: __dirname,
})(nextConfig);

module.exports = nextConfig;

Error:

"next/font" requires SWC although Babel is being used due to a custom babel config being present.

Answer №1

Setting up is a breeze. Begin by installing the following plugin:

npm install --save-dev @stylexjs/nextjs-plugin

If you don't already have one, create a .babelrc.js file in the root directory and add these configurations:

module.exports = {
  presets: ['next/babel'],
  plugins: [
    [
      '@stylexjs/babel-plugin',
      {
        dev: process.env.NODE_ENV === 'development',
        runtimeInjection: false,
        genConditionalClasses: true,
        treeshakeCompensation: true,
        unstable_moduleResolution: {
          type: 'commonJS',
          rootDir: __dirname,
        },
      },
    ],
  ],
};

Update the next.config.js file with these settings:

const stylexPlugin = require('@stylexjs/nextjs-plugin');

const nextConfig = {
  reactStrictMode: true,
}

module.exports = stylexPlugin({
  rootDir: __dirname,
})(nextConfig);

You're now all set to delve into the world of stylex.

Answer №2

Avoid using next/font in projects that utilize Babel as it is not supported. Make sure to remove any instances of next/font from your codebase.

Answer №3

To remove the font installed by create-next-app, follow these steps:

In layout.tsx, delete the following lines

import { Inter } from next/font/google'

and

const inter = Inter({ subsets: ["latin"] });

These lines are usually found at line 3 and 5 respectively.

Additionally, remove the classname on body (also in layout.tsx), so change this line

<body className={inter.className}>{children}</body>

to

<body>{children}</body>

StyleX has provided an example for Next.js. You can check out the next.config.ts and .babel.rc files here:

https://github.com/facebook/stylex/blob/main/apps/nextjs-example/next.config.js

https://github.com/facebook/stylex/blob/main/apps/nextjs-example/.babelrc.js

Once you have completed these steps, running npm run dev will show the following output:

> <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aac4cfd2dec0d987c8c6c5cdea9a849b849a">[email protected]</a> predev
> npm run clean


> <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9df3f8e5e9f7eeb0fff1f2faddadb3acb3ad">[email protected]</a> clean
> rimraf .next


> <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="610f0419150b124c030d0e0621514f504f51">[email protected]</a> dev
> next dev

   ▲ Next.js 14.1.4
   - Local:        http://localhost:3000

   Disabled SWC as replacement for Babel because of custom Babel configuration ".babelrc.js" https://nextjs.org/docs/messages/swc-disabled
 ✓ Ready in 2.2s

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Introducing a new addition to the Material UI palette: an extra color to amplify your theme and integrate seamlessly into your design just like Primary and

One of the new custom colors I've added to the palette is blue: const rawTheme = createMuiTheme({ palette: { primary: { light: '#7ED321', main: '#417505', dark: '#2B5101', contrastText: &apo ...

What causes setInterval to exponentially increase its logging with each re-render?

import { useState } from "react"; function ParentComp(props){ console.log("parent component is rendering"); const [person, setPerson] = useState({ firstName: "First" }); setInterval(() => { setPerson({ firstName: "Second" }); }, 6000); r ...

Retrieve the httponly cookie from NextJS before making a fetch request to an external API

Within my NextJS application, I am utilizing an external API for user authentication and handling other API requests. Specifically, I have integrated a Flask app as the external API. The process involves sending credentials to the API upon login, which the ...

A guide on accessing Textfield input values in Redux-form while utilizing MaterialUI

The objective is to retrieve input values from a material UI component and transmit them to an action creator within a handleSubmit function. <Field name='email' component={email => <TextField fullWidth autoComplete='off' clas ...

Modifying the values of various data types within a function

Is there a more refined approach to enhancing updateWidget() in order to address the warning in the else scenario? type Widget = { name: string; quantity: number; properties: Record<string,any> } const widget: Widget = { name: " ...

Securing Next.js with JWT authentication

Presently, my backend provides me with an access and refresh token for user authorization. In a past project, I stored tokens in local storage for client-side user authentication. As my current project is restricted to registered users only, I have implem ...

Execute a simulated click on the Material-UI Tabbar using a programmatic approach or keyboard shortcut

In my electron/react application, I am implementing Material UI tabs in the following manner: <Tabs> <Tab label="View1" > <View1 /> </Tab> <Tab label="View2"> ...

Is there a way to assign multiple paths to a single page within the NextJS pages directory?

I'm currently working on a project that has two different themes, and I have the ability to switch between them based on the environment. Everything works perfectly, but I'm encountering an issue with paths. Some pages should open with different ...

Switch between light and dark modes with the MUI theme toggle in the header (AppBar)

I'm currently working on implementing a feature that allows users to switch between dark and light themes in my web app. The challenge I am facing is how to ensure that this theme change functionality is available throughout the entire app, not just i ...

I found myself pondering the method to achieve the slightly blue tinted box that sits behind the image

Can you assist me in achieving this specific look? I have my MUI app bar and home page set up, but I'm unsure how to create the blue-ish box behind the image. Should I place the container within my app bar or integrate it into my homepage file? Additi ...

Enhancing Material UI Autocomplete with Custom Styling

I need help adjusting the padding to align the icon to the right side in an AutoComplete Material UI component. The current styling is being overridden by this specific style: .MuiAutocomplete-hasPopupIcon.MuiAutocomplete-hasClearIcon .MuiAutocomplete-inp ...

Select multiple options by checking checkboxes in each row using React

Is it possible to display multiple select checkboxes with more than one per row? For example, I have four options [a, b, c, d]. How can I arrange it to have 2 options per row, totaling 2 rows instead of having 1 option per row for 4 rows? ☑a ☑b ☑c ...

What is the best way to retrieve the URL query parameters in a Node.js environment?

How can I retrieve URL query parameters in Node.js using TypeScript? Below is my attempted code: /** * My Server app */ import * as Http from "http"; import * as url from "url"; import { HttpServer } from "./HttpServer"; import { TaxCalculator } from ". ...

Encountered a type error during project compilation: "Type '(e: ChangeEvent<{ value: string[] | unknown; }>) => void' error occurred."

I recently started working with react and I'm facing an issue with a CustomMultiSelect component in my project. When I try to call events in another component, I encounter the following error during the project build: ERROR: [BUILD] Failed to compile ...

Changing the MaterialUI icon when it is clicked

Each item in a list has an "AddIcon". Upon clicking the icon, I want to replace it with a "BlockIcon" based on its unique "id". import React from 'react' import {List, ListItem} from '@material-ui/core' import AddCircleIcon from ' ...

Centering an image on a webpage using CSS

Here is the code I am using for displaying my image: return <div class="imgContainer"><img src={broomAndText} alt="broomAndText" /></div> In my css file, I have included the following styling: .imgContainer { tex ...

Beware: Inaccessible code detected in Reactjs usage

Currently, I am working on a ReactJS project where I have integrated two components - PrescriptionIndex and PrescriptionNew. Let's start with the 'PrescriptionNew' component: import React, { Component } from 'react'; import Flo ...

Step-by-step guide to crafting curved bars in Material-UI X visualizations

Is it possible to create a MUI X Chart with rounded corners from the top? Take a look at this Image import { BarChart, LineChart, PieChart } from "@mui/x-charts"; const users = [ { label: "bachir", value: 1730, }, { label: "Othma ...

Convert checkbox choices to strings stored in an array within an object

I have a intricate object structure JSON{ alpha{ array1[ obj1{}, obj2{} ] } } In addition to array1, I need to include another array: array2 that will only consist of strin ...

next-images encountered an error during parsing: Unexpected character ''

Having trouble loading images dynamically with next-images: //Working <Image src={require(`../../images/exampleImage.jpg` )}/> However, I want to use a dynamic URL like this: //Not working <img src={require(`../../images/${image}.jpg` )}/> Th ...