Turned off SWC as a substitute for Babel due to the specific Babel setup in Next.js version 14

While working on my Next.js 14 project, I encountered an issue when running npm run dev. The error message I received is as follows:

npm run dev

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

 ⚠ Port 3000 is in use, trying 3001 instead.
   ▲ Next.js 14.1.0
   - Local:        http://localhost:3001

 ⚠ Invalid next.config.mjs options detected: 
 ⚠     Unrecognized key(s) in object: 'optimizeFonts' at "experimental"
 ⚠ See more info here: https://nextjs.org/docs/messages/invalid-next-config
   Disabled SWC as replacement for Babel because of custom Babel configuration ".babelrc" https://nextjs.org/docs/messages/swc-disabled
 ✓ Ready in 1350ms
   Using external babel configuration from /Users/(omission)/Documents/Personal/React/my-portfolio/.babelrc
 ⚠ It looks like there is a custom Babel configuration that can be removed.
 ○ Compiling /not-found ...
 ⨯ ./src/app/layout.tsx:2:1
Syntax error: "next/font" requires SWC although Babel is being used due to a custom babel config being present.
Read more: https://nextjs.org/docs/messages/babel-font-loader-conflict
 ⨯ ./src/app/layout.tsx:2:1
Syntax error: "next/font" requires SWC although Babel is being used due to a custom babel config being present.
Read more: https://nextjs.org/docs/messages/babel-font-loader-conflict
 ✓ Compiled / in 80ms (417 modules)
 ⚠ Fast Refresh had to perform a full reload. Read more: https://nextjs.org/docs/messages/fast-refresh-reload

The root cause of this error seems to be a conflict between SWC's "next/font" settings and my custom Babel configuration setup. I continued using Babel in my project as I needed it to test my Next.js components with Jest.

Initially, I followed the guidelines outlined on this particular website(in Japanese), which involved configuring a custom Babel setup.

Steps mentioned on the website

  1. Install the necessary packages (assuming you already have a Next.js project set up)
npm i -D jest @testing-library/react @types/jest @testing-library/jest-dom @testing-library/dom babel-jest @testing-library/user-event jest-css-modules
  1. Adjust the .babelrc file accordingly
{
    "presets": ["next/babel"]
}
  1. Add the Jest configuration to package.json
"jest": {
    "testPathIgnorePatterns": [
        "<rootDir>/.next/",         // Exclude from tests
        "<rootDir>/node_modules/"
    ],
    "moduleNameMapper": {          // Mock CSS files using jest-css-modules
        "\\.(css)$": "<rootDir>/node_modules/jest-css-modules"
    }
}
  1. Include a test script in your package.json
"scripts": {
    ...
    "test": "jest --env=jsdom --verbose"  // Add this
},

Example of the test script:

import "@testing-library/jest-dom/";
import { render, screen } from "@testing-library/react";
import Page from "../src/app/page";

// testing the page component

test("renders the page", () => {
  render(<Page />);
  expect(screen.getByText(/Get started by editing/)).toBeInTheDocument();
});

Project structure overview:

https://i.sstatic.net/E6HEq.png

Attempts made to resolve the issue:

- Disable font optimization feature: Even after disabling the font optimization feature in my next.config.mjs file with the provided code snippet, the same error persisted when accessing my local host.
/** @type {import('next').NextConfig} */
const nextConfig = {
  experimental: {
    optimizeFonts: false,
  },
};

export default nextConfig;

Environment details:

  • Node.js version: v18.17.0
  • Next.js version: 14.1.0
  • TypeScript version: 5.3.3
  • OS: macOS Monterey version 12.6.7

Are there any recommendations to troubleshoot this issue?
Alternatively, is there another way to utilize Jest within my project efficiently?
Any guidance or suggestions would be greatly appreciated.

Answer №1

Utilizing Babel in Conjunction with SWC

If you desire to leverage SWC alongside an existing .babelrc file, it is possible to enforce this configuration within your next.config.js file.

SWC disabled | Next.js docs

This approach ensures that disabling font optimization or any other SWC features is not necessary.

Substitute for Babel

I do not recommend sticking with Babel solely for Jest compatibility. SWC can be seamlessly integrated with Jest by adding the following snippet to your jest.config.js file:

const nextJest = require('next/jest')
 
/** @type {import('jest').Config} */
const createJestConfig = nextJest({
  // Specify the path to your Next.js app to load next.config.js and .env files in your test environment
  dir: './',
})
 
// Add any custom configurations to be passed to Jest
const config = {
  coverageProvider: 'v8',
  testEnvironment: 'jsdom',
  // Include additional setup options before each test execution
  // setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
}
 
// Exporting createJestConfig in this manner ensures that next/jest can access the asynchronous Next.js configuration
module.exports = createJestConfig(config)

Refer to Testing: Jest | Next.js docs.

Opt for Vitest over Jest

In my personal opinion, using Vitest is the way to go. Explore the Vitest comparison to comprehend its benefits. Vitest also serves as a seamless replacement for Jest. Check out this article for guidance on transitioning from Jest to Vitest.

Answer №2

If you're looking to streamline your project, consider ditching Babel and opting for the NextJS SWC compiler when running Jest.

Check out this link for more information

To make the switch, simply remove all babel configuration files and uninstall Babel from your project entirely.

Afterwards, create a jest.config.js file with code similar to the example below:

const nextJest = require('next/jest')

// Customize the path to your Next.js app for loading next.config.js and .env files
const createJestConfig = nextJest({ dir: './' })

// Add any additional custom configurations for Jest
const customJestConfig = {
    moduleNameMapper: {
        "^@/(.*)$": "<rootDir>/src/$1"
    }
}

// Export createJestConfig in a way that allows next/jest to load the Next.js configuration asynchronously
module.exports = createJestConfig(customJestConfig)

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

What advantages come with utilizing the NextJS API?

As I prepare to develop the API for my service, I'm considering whether using NextJS API integration offers any advantages. While it may not align perfectly with my preferences and lacks the extensive resources of expressJS, there are integrations ava ...

Issue with subscribing to a shared service in Angular 2

I've encountered some challenges with BehaviorSubject while using a shared service across three components: import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; @Injectable() export ...

Encountering a Typescript issue while trying to access two distinct values dynamically from within a single object

Currently, I'm developing a component library and facing an issue with a TypeScript error: An Element implicitly has an 'any' type due to the expression of type 'levelTypes | semanticTypes' being unable to index type '{ level1 ...

Sharing data between components in Angular2 can be achieved through the use of services

In my Angular2 app, I need to share an object between components. Here is how I'm attempting to do this: First component source code: /* app.component.ts */ // ...imports import {ConfigService} from './config.service'; @Component({ sel ...

Challenge with module declaration in index.d.ts during upgrade from Angular 8 to 9 (excluding Material)

In my index.d.ts file, I have declared two modules like so: declare module 'googlemaps'; declare module 'detect-resize'; Previously, these declarations worked perfectly fine, allowing me to utilize these modules. The googlemaps module ...

The Angular MatStepper is unable to detect saved values from two string arrays, although it is able to detect values from a different string array

In my application, there is a MatStepper component that facilitates navigation through the signup flow. A method exists to load cached values when available, causing the MatStepper to skip to Page 2. Subsequently, another method pre-fills the form with the ...

Angular - Loading images on the fly

After scouring numerous resources, I couldn't find a resolution to my issue. For your information, I am utilizing ASP.net Core 2.0's default angular project In the process of developing an Angular application, I am faced with the challenge of ...

Failure of React to connect event handlers

LATEST UPDATE: After removing the output entry from my webpack configuration, the React event listeners are now functioning correctly. Currently, I am diving into the world of hand-rolling webpack configurations for a React/TypeScript application for the ...

Transform the IO type to an array of Either in functional programming with the fp-ts

Looking for assistance with implementing this in fp-ts. Can someone provide guidance? const $ = cheerio.load('some text'); const tests = $('table tr').get() .map(row => $(row).find('a')) .map(link => link.attr(&apos ...

What is the best way to generate conditional test scenarios with Protractor for testing?

Currently, there are certain test cases that I need to run only under specific conditions. it ('user can successfully log in', function() { if(siteAllowsLogin) { ..... } The problem with the above approach is that even when sitesNo ...

Answer found: How to effectively filter data arrays in a React client application

I've been working on mapping the GraphQL data onto a React app and I'm facing an issue with making the filtration dynamic for user input. Currently, I am using .filter() to apply client-side filtration but struggling to figure out how to make it ...

Disable the click event on a specific child element to prevent the NextJS `Link` from being triggered

I am facing an issue with my Link component that wraps a div containing multiple children. I need to disable the functionality of the Link when a specific child element is clicked. How should I go about implementing this? <Link href={"go\to&bs ...

Incorrectly selecting an overload in a Typescript partial interface can lead to errors

My attempt to define an overload for my function using a Partial interface overloading is causing typescript to select the incorrect overload interface Args { _id: string; name: string; } interface Result { _id: string; name: string; } function my ...

A More Straightforward Approach to Unsubscribing from Observables in Angular 7

Is there a way to simplify the process of automatically unsubscribing from Observables when a component is destroyed using takeUntil? It becomes tedious having to repeat the same code in multiple components. I am looking for a solution that allows me to a ...

TypeScript integrated Cypress code coverage plugin

I've been attempting to integrate the @cypress/code-coverage plugin with TypeScript in my project, but so far I haven't had any success. Here is a breakdown of the steps I've taken thus far: Followed all the instructions outlined in https:/ ...

How to delete an item from an object in TypeScript

Can you help with filtering an object in Angular or TypeScript to eliminate objects with empty values, such as removing objects where annualRent === null? Additionally, what method can we use to round a number like 2.833333333333335 to 2.83 and remove the ...

Seamless database migrations using sequelize and typescript

I've been exploring the concept of generating migration files for models that already exist. When I use the "force: true" mode, tables are automatically created in the database, so I find it hard to believe that creating migration files automatically ...

Exploring the concept of data sharing in the latest version of Next.JS - Server

When using App Router in Next.JS 13 Server Components, the challenge arises of not being able to use context. What would be the most effective method for sharing data between various server components? I have a main layout.tsx along with several nested la ...

Tips for updating the border color of a button:

Struggling to alter the border color of a button Attempting borderColor attribute proved futile: borderColor: '#FFFFFF' Anticipated result Code snippet: headerBtn: { backgroundColor: 'black', fontSize: '16px', f ...

Using Firestore queries in your NodeJS application

Here's a query that is functioning as intended: const queryRef = firestore.collection('playlists').where('machines', 'array-contains', id) const snapshot = await queryRef.get() ... const playlist = document.data() as Pl ...