What are the steps to set up NextJS 12.2 with SWC, Jest, Eslint, and Typescript for optimal configuration?

Having trouble resolving an error with Next/Babel in Jest files while using VSCode. Any suggestions on how to fix this?

I am currently working with NextJS and SWC, and I have "extends": "next" set in my .eslintrc file.

Error message: Parsing error - Cannot locate module 'next/babel'

Here is a snippet from my package.json file:

{
...
  "dependencies": {
    "@emotion/cache": "^11.9.3",
    "@emotion/react": "^11.9.3",
    "@emotion/server": "^11.4.0",
    "@emotion/styled": "^11.9.3",
    "@mui/icons-material": "^5.8.4",
    "@mui/material": "^5.9.2",
    "next": "12.2.3",
    "react": "18.2.0",
    "react-dom": "18.2.0",
  },
  "devDependencies": {
    "@swc/core": "^1.2.220",
    "@swc/jest": "^0.2.22",
    "@testing-library/dom": "^8.16.0",
    "@testing-library/jest-dom": "^5.16.2",
    "@testing-library/react": "^13.3.0",
    "@testing-library/user-event": "14.3.0",
    "@types/node": "^18.6.3",
    "@types/react": "18.0.15",
    "@types/testing-library__jest-dom": "^5.14.5",
    "eslint": "8.20.0",
    "eslint-plugin-testing-library": "^5.6.0",
    "jest": "^28.1.3",
    "jest-environment-jsdom": "^28.1.3",
    "next-transpile-modules": "9.0.0",
    "typescript": "^4.6.2"
}

Answer №1

The issue stemmed from the behavior of file types and extensions. The problem was caused by using Module.Exports with a .eslintrc.js file. Switching to a .eslintrc file in json format resolved the error.

// .eslintrc.js - Not functional

// Commented out for testing
// do this module.exports = require("baseconfig/eslint-preset"); 

module.exports = {
    extends: ["prettier", "next/core-web-vitals"],
    plugins: ["testing-library"],
    settings: {
      next: {
        rootDir: ["apps/*/", "packages/*/"],
      },
    },
    rules: {
      "@next/next/no-html-link-for-pages": "off",
    },
    overrides: [
      // Only applies Testing Library lint rules in test files
      {
        "files": [
          "**/__tests__/**/*.[jt]s?(x)",
          "**/?(*.)+(spec|test).[jt]s?(x)"
        ],
        "extends": ["plugin:testing-library/react"]
      }
    ]
  };
// .eslintrc - Functional
{
    "extends": ["prettier", "next/core-web-vitals"],
    "plugins": ["testing-library"],
    "settings": {
      "next": {
        "rootDir": ["apps/*/", "packages/*/"],
      },
    },
    "rules": {
      "@next/next/no-html-link-for-pages": "off",
    },
    "overrides": [
      // Only uses Testing Library lint rules in test files
      {
        "files": [
          "**/__tests__/**/*.[jt]s?(x)",
          "**/?(*.)+(spec|test).[jt]s?(x)"
        ],
        "extends": ["plugin:testing-library/react"]
      }
    ]
  }

Answer №2

Have you already set up your jest.config.js file as recommended in the official Next.js documentation? Visit this link for more information

  transform: {
    '\\.[jt]sx?$': ['babel-jest', { presets: ['next/babel'] }],
  },

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

Building Components on the Fly with Angular 5

I've been utilizing code similar to this to dynamically generate components within my application. These components need to support dynamic inputs. However, upon attempting to upgrade to Angular 5, I've encountered an issue with ReflectiveInjecto ...

Passing NextJS props as undefined can lead to unexpected behavior and

Struggling with dynamically passing props to output different photo galleries on various pages. One of the three props works fine, while the others are undefined and trigger a warning about an array with more than one element being passed to a title elemen ...

Error 404: Next.js Navigation Not Detected

I've recently launched a new Next.js project and I'm currently working on implementing client-side navigation. However, I am facing an issue where I am unable to navigate to routes other than "/". Layout.js : import "../styles/globals.css&q ...

Encountering problems with NextJS server-side rendering when using react-d3-tree

I took a look at issue number 40 and 95 on the react-d3-tree github, but couldn't find a solution on StackOverflow. My goal is to implement the parseJSON method to generate a tree diagram using my own JSON file from the project folder. Initially, I c ...

Tips for designing unique input placeholders in react and next.js

I am facing a challenge in applying custom CSS to the placeholder text within a React input field. My requirement is to have multiple CSS attributes for different parts of the placeholder text, rather than applying one style to the entire placeholder. The ...

Troubleshooting font color issues with PrimeNG charts in Angular

I have a chart and I am looking to modify the color of the labels The gray labels on the chart need to be changed to white for better readability Here is my code snippet: HTML5: <div class="box-result"> <h5 class="title-resul ...

What is the syntax for creating ES6 arrow functions in TypeScript?

Without a doubt, TypeScript is the way to go for JavaScript projects. Its advantages are numerous, but one of the standout features is typed variables. Arrow functions, like the one below, are also fantastic: const arFunc = ({ n, m }) => console.log(`$ ...

vue.js libs requiring "new ..." are being scolded by eslint for their misspelling

When working with Vue libraries, such as Swiper, that require the use of 'new …' in the script section, I encounter ESlint errors no matter how I try to write it. Even though 'new ...' works perfectly fine in the frontend, ESlint cont ...

The options passed to createReadStream in TypeScript do not accept {start: 90, end: 99}

After updating to TypeScript 1.6.2, I encountered an issue with my call to createReadStream(). The problem arises because the type definition in node.d.ts does not recognize 'start' and 'end' in the options parameter. var st = fs.crea ...

Guide on positioning a span element to the left using the margin auto property in CSS for Angular 4

Having trouble with moving numbers highlighted to the left with names in CSS. I've tried using flex direction and margin auto but can't achieve the desired result. Here is my HTML code: <section class="favorites"> <div class="category" ...

Developing Your Own Local Variable in Angular with Custom Structural Directive ngForIn

I am hoping for a clear understanding of this situation. To address the issue, I developed a custom ngForIn directive to extract the keys from an object. It functions correctly with the code provided below: import {Directive, Input, OnChanges, SimpleChan ...

Typescript's way of mocking fetch for testing purposes

I have a query regarding the following code snippet: import useCountry from './useCountry'; import { renderHook } from '@testing-library/react-hooks'; import { enableFetchMocks } from 'jest-fetch-mock'; enableFetchMocks(); i ...

Type of tuple without a specific order

Exploring Typescript typings has led me to ponder how to create a type that is a tuple with unordered element types. For example: type SimpleTuple = [number, string]; const tup1: SimpleTuple = [7, `7`]; // Valid const tup2: SimpleTuple = [`7`, 7]; // &ap ...

TypeScript: displaying parameters

variable_field = [["S",".","."],[".","#","."],[".",".","T"]]; <ng-template ngFor let-array [ngForOf]="field_array" let-x="index"> <ng-t ...

Unused code splitting chunk in React production build would improve performance and efficiency of

When running the command npm run build, a build directory is generated with js chunks. I have observed an unfamiliar file named [number].[hash].chunk.js that does not appear in the list of entrypoints in the asset-manifest.json file. Instead, this mysteri ...

Guide on how to connect several Subjects within an object literal to their corresponding Observables in another object literal

I am currently developing a class using Angular and I need to share multiple states associated with that class. To accomplish this, I have created several instances of BehaviorSubject private subjects = { a : new BehaviorSubject<A>(this.a), b ...

Files are nowhere to be found when setting up an angular project

After creating an Angular project, I noticed that some key files were missing in the initial setup, such as app.modules.ts and app-routing.modules.ts The project was generated using the command ng new name Here is a screenshot displaying all the files th ...

Guide for integrating the shadcn/ui Range Date Picker within a Form

Encountering an issue with using The Range Date Picker within the Form component. Specifically, I am looking to store {from, to} values of the range in an object, however, utilizing an object as a Form field value results in error messages not functioning ...

twice the custom nextjs responsive detection hook is being called

A custom hook has been developed that detects device on reload and resize events. import { useState, useEffect, useRef, useCallback } from "react"; export const DEVICE_SIZES_VALUE = { MOBILE: 576, TABLET: 768, DESKTOP: 992, LARGE_DESKTOP ...

What is the best way to create a generic function parameter for a single property of an object?

I am trying to refactor a generic function into accepting parameters as a single object function test<T>(a: string, b: T, c: number) Instead, I want the function to receive an object like this: function test(params: {a: string; b: T, c: number}) I ...