What is the best way to implement Linaria with NextJS?

I'm excited to start using the Linaria library in my NextJS project. I followed the documentation, but encountered an error.

The error message states: Global CSS cannot be imported from files other than your Custom . Please move all global CSS imports to pages/_app.js. For more information, visit:

Although I understand the error, I am curious about how to properly integrate Linaria with NextJS.

  • .babelrc
{
  "presets": ["next/babel", "linaria/babel"],
}
  • next.config.js
const path = require("path");

module.exports = {
  webpackDevMiddleware: (config) => {
    config.watchOptions = {
      poll: 1000,
      aggregateTimeout: 300,
    };
    return config;
  },

  webpack: (config) => {
    config.module.rules.push({
      test: /\.tsx$/,
      use: [
        {
          loader: "linaria/loader",
          options: {
            sourceMap: process.env.NODE_ENV !== "production",
          },
        },
      ],
    });

    return config;
  },
};

Answer №1

There is a current linaria problem on this subject. Many individuals are experiencing positive outcomes by utilizing the following next.config.js setup:

const withCSS = require('@zeit/next-css');

module.exports = withCSS({
  webpack(config) {
    // locate the rule without prior knowledge of its placement
    const jsLoaderRule = config.module.rules.find(
      (rule) => rule.test instanceof RegExp && rule.test.test('.js')
    );
    const linariaLoader = {
      loader: 'linaria/loader',
      options: {
        sourceMap: process.env.NODE_ENV !== 'production',
      },
    };
    if (Array.isArray(jsLoaderRule.use)) {
      jsLoaderRule.use.push(linariaLoader);
    } else {
      jsLoaderRule.use = [jsLoaderRule.use, linariaLoader];
    }
    return config;
  },
});

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

Having trouble reaching the subpages of my NextJS static site on S3 through CloudFront when public access is restricted

I have set up CloudFront to host my NextJS static site using an S3 bucket. I purposely restricted public access to the S3 bucket, so the only way to view the site is through the CloudFront URL (I implemented Origin Access Control "OAC" on the CloudFront di ...

I'm having trouble connecting to port 3000 on my Docker container from the browser

I have dockerized my application using Laravel, Nginx, and MySQL. Below are the docker-compose file and Dockerfiles used: docker-compose.yaml version: '3.8' services: # Application app: container_name: app build: context: . ...

What could be causing a momentary 404 error when I click on a next.js `Link` that connects to an API endpoint before redirecting to the intended page?

Hello there, I recently followed a tutorial on adding authentication with Passport to Next.js from this resource: https://auth0.com/blog/next-js-authentication-tutorial/ However, I encountered a minor issue. When I click the "/login" Link in my Next.js ...

The 'required' validator in Mongoose seems to be malfunctioning

I've been attempting to validate the request body against a Mongoose model that has 'required' validators, but I haven't been successful in achieving the desired outcome so far. My setup involves using Next.js API routes connected to Mo ...

Ways to implement pagination or filtering in Next.js

Seeking a solution to incorporate pagination or filtering in my web application through traditional page routing. Is Client Side data fetching necessary? If query strings change, how can I prevent a re-render of the page content? Avoiding fetching all data ...

Typescript is struggling to accurately infer extended types in some cases

My goal is to optimize the body of a NextApiRequest for TypeScript. I currently have this code snippet: // This is a type from a library I've imported export interface NextApiRequest { query: Partial<{ [key: string]: string | string[]; ...

VSCode is experiencing issues with recognizing .env* files for markup purposes and is also failing to recognize .env.local.* files

Current Environment: Utilizing NextJs, React, and VsCode Noticing a problem with syntax highlighting in my VSCODE editor. I have installed the following extensions: ENV DotEnv As per suggestions, I updated my json configuration file as follows: " ...

Tips for preventing a React component from re-fetching data when navigating back using the browser button

In my React app using Next.js and the Next Link for routing, I have two pages set up: /product-list?year=2020 and /product-list/details?year=2020&month=4 Within the pages/product-list.js file, I am utilizing React router to grab the query parameter ye ...

Customizing App (directory) elements in next.js 13

Imagine having this directory organization: https://i.stack.imgur.com/Hd5gu.png Is there a method for loading the component from the custom folder instead of the default one in the app folder? In case the custom folder does not have that component, can t ...

Component not appearing in Storybook during rendering

I'm trying to incorporate the MUI Button Component into my storybook and then dynamically change MUI attributes like variant, color, and disabled status directly from the storybook. While I was successful in doing this with a simple plain HTML button, ...

A New Approach to Fetching Data in Next.js 13.2 using Sanity

Simply put, the main issue revolves around my usage of Sanity as I delve into learning it. While referencing their documentation at , they make use of getStaticProps. Unfortunately, with my utilization of Next.js 13.2 experimental app directory, this speci ...

Leveraging the Apollo client cache in Next.js with getServerSideProps

Exploring the world of Next.js with Apollo Client has been quite an adventure for me. One challenge I am facing is establishing a smooth workflow between the server and client sides. In my SSR page, I execute a query within getServerSideProps and then tran ...

Is the pre-building of pages in React/Next.js causing a slowdown in the application?

I recently embarked on studying the Next.js framework and came across a question. Consider a scenario where I have a dynamic route for users like users/profile/[id].js. If I attempt to pre-build them with Static generation, wouldn't this potentially ...

When attempting to launch the Next.js DEV server using a specific IP address and port, an error message of "get

Running a development server on my local area network (LAN) has always worked fine for me in the past, but recently I've been encountering an error when trying to run servers like Vite or NextJS on 192.168.1.7:3000. Here is a screenshot of the error ...

The issue of WooCommerce GraphQL API not returning a comprehensive list of product variations is causing frustration among users

I'm currently working on a project that involves WooCommerce integration with WordPress and utilizing GraphQL to retrieve product variations. One issue I've encountered is that the GraphQL API is only returning 10 out of 12 variations for a speci ...

Unable to change Bootstrap variables within a Next.js project

I'm having trouble changing the primary color in Bootstrap within my NextJS project. I've tried different methods but nothing seems to work as expected. Here is the code snippet from my "globals.scss" file that I imported in "_app.js": $primary: ...

Building state from multiple child components in Next.js/React: Best Practices

To better illustrate this concept, I suggest checking out this codesandbox link. This is a follow-up to my previous question on Stack Overflow, which can provide additional context. Currently, when interacting with the child elements (such as inputs), th ...

Exciting Update: Next.js V13 revalidate not triggering post router.push

Currently using Next.js version 13 for app routing, I've encountered an issue with the revalidate feature not triggering after a router.push call. Within my project, users have the ability to create blog posts on the /blog/create page. Once a post is ...

Receiving an error unexpectedly when using 'use client' in NEXT JS 13

I am currently utilizing the experimental app directory that comes with TypeScript support. This specific code pertains to a Server component. export default function SimpleComponent() { return ( <> <h1>Hello</h1> ...

SWR NextJS error remains unhandled despite being thrown

I'm struggling to manage errors thrown in my SWR fetcher. Currently, whenever an error is thrown, my app stops working and I see an "Unhandled Runtime Error". What I've been doing is throwing the error inside the fetcher function. Here's th ...