Converting an npm module to work with Next.js

I have been attempting to transpile the module "react-device-detect" from node_modules, but so far I have been unsuccessful. Here is what I have tried:

module.exports = withLess({
  webpack: (config, { isServer, defaultLoaders }) => {
    // other configs
    config.module.rules.push({
      test: /\\.+(ts|tsx)$/,
      include: [path.join(__dirname, 'node_modules/react-device-detect')],
      // exclude: /node_modules/,
      use: [{ loader: 'ts-loader' }],
    });

    config.module.rules.push({
      test: /\\.+(js|jsx)$/,
      include: [path.join(__dirname, 'node_modules/react-device-detect')],
      // exclude: /node_modules/,
      use: [{ loader: 'babel-loader' }],
    });
    return config;
  },
});

I have also experimented with applying the rules individually, but unfortunately without success.

UPDATE 1: Refer to complete next.config.js configurations @felixmosh

const webpack = require("webpack");
const withLess = require("@zeit/next-less");
const { parsed: localEnv } = require("dotenv").config();
require("dotenv").config({
  path: process.env.NODE_ENV === "production" ? ".env.production" : ".env"
});
const Dotenv = require("dotenv-webpack");

module.exports = withLess({
  webpack: (config, { isServer }) => {
    // Fixes npm packages that depend on `fs` module
    config.node = {
      fs: "empty"
    };
    // add env variables on client end
    config.plugins.push(new webpack.EnvironmentPlugin(localEnv));
    config.plugins.push(new Dotenv());

    if (!isServer) {
      config.resolve.alias["@sentry/node"] = "@sentry/browser";
    }
    return config;
  }
});

UPDATE 2:

It appears that next-transpile-modules does not integrate smoothly with next-i18next. In the console of IE browser, I encountered the following error:

'exports' is undefined

When running npm run build, errors like the ones below surfaced:

./utils.js
Attempted import error: 'isMobileSafari' is not exported from 'react-device-detect'.

./utils.js
Attempted import error: 'isMobileSafari' is not exported from 'react-device-detect'.

./utils.js
Attempted import error: 'osName' is not exported from 'react-device-detect'.

Running npm start led to this output:

react-i18next:: i18n.languages were undefined or empty undefined

Answer №1

You can easily transpile specific modules using an NPM package called next-transpile-modules. Simply specify the modules you want to transpile in your code.

// next.config.js
const withTM = require('next-transpile-modules')(['somemodule', 'and-another']); // include the modules for transpilation

module.exports = withTM(withLess({
  ... // add your custom configurations here

}));

Edit:

Update: Starting from Next 13.1, there is now built-in support for transpiling specified packages.

// next.config.js

const nextConfig = {
  transpilePackages: ['@acme/ui', 'lodash-es'],
};

module.exports = nextConfig;

Answer №2

Starting with version 13.1 of Next.JS, you now have the ability to utilize the transpilePackages property within your next.config.js file.

const nextConfig = {
  transpilePackages: ['the-npm-package'],
};

module.exports = nextConfig;

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

Setting up Next.js rendering within Express routing: A step-by-step guide

app.js const express = require('express'); const next = require('next'); const port = parseInt(process.env.PORT, 10) || 3000; const dev = process.env.NODE_ENV !== 'production'; const app = next({ dev }); const handle = app.ge ...

Is it crucial to commit to memory a Tiny/Affordable Component? - ReactJS

Imagine having a child component that simply returns a div element Child Component : function Child() { return <div className={styles.alertBox}>No Data Found</div>; } Every time the parent state changes, this child component will re-render. ...

How can you resolve the "Unexpected Token Operator (>)" error while bundling a React application?

I am currently facing challenges when trying to create the distributable package for a React application. My attempt to run the following command has resulted in an error: rimraf dist && env-cmd .env cross-env NODE_ENV=production webpack -p --con ...

Having trouble resolving the module path 'fs/promises' while using Next.js and eslint

Recently, I began working on a Next.js application and successfully configured eslint to ensure code quality. Here is the list of dev dependencies for my Next.js app: "devDependencies": { "babel-eslint": "^10.1.0", &qu ...

Error in CPanel: NextJS Static Export is failing to load due to missing JS chunks, CSS, and SVG files

Recently, I have discovered that when using VSCode Live server to host static files locally, everything seems to work perfectly. This led me to believe that the issue may lie in how CPanel deals with static files. Could it be causing the 404 not found erro ...

Encountering an error with the Firebase cloud functions SDK when making a

I have a Python-based Firebase cloud function named hello_world_fn: from firebase_functions import https_fn from firebase_admin import firestore import google.cloud.firestore @https_fn.on_request() def hello_world_fn(req: https_fn.Request) -> https_fn. ...

Encountering an Issue with Dynamic Imports in Cypress Tests Using Typescript: Error Loading Chunk 1

I've been experimenting with dynamic imports in my Cypress tests, for example using inputModule = await import('../../__tests__/testCases/baseInput'); However, I encountered an issue with the following error message: ChunkLoadError: Loading ...

Having trouble setting the state of an array using NextJS useState?

I'm facing an issue where the array saved to a useState state is not updating properly. Despite properly returning values for the variable first, the variable "data" remains an empty array. Interestingly, adding a console.log("restart") statement und ...

Error encountered while trying to import the Turborepo UI package into Next.js: It appears that an appropriate loader may be required

Currently, I am working on a project using next.js 13.1.1 and setting up a monoRepo-based project with turborepo for the first time. My goal is to incorporate: @next/bundle-analyzer @sentry/nextjs @next-pwa When these configurations are not used, everyth ...

Place a Material-UI TextField alongside a Label

I've been searching everywhere, but I can't figure it out. My goal is to place a TextField element next to a label (and not inside or touching the border of the TextField) like in this image: Desired Result Label <____> TextField This sp ...

VueJS offers a mixin that is accessible worldwide

I'm looking to create a global mixin that is accessible everywhere, but not automatically inserted into every component. I don't want to use Vue.mixin({...}); Following the guidelines from this source, I have structured my project accordingly. Y ...

Unable to modify the theme provider in Styled Components

Currently, I am attempting to customize the interface of the PancakeSwap exchange by forking it from GitHub. However, I have encountered difficulties in modifying not only the header nav panel but also around 80% of the other React TypeScript components. ...

What is the process for customizing the heading titles on various pages within the Next.js application directory?

Within the app directory of Next.js 13, I have a default root layout setup: import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <head> <title>Create ...

Is there a way to display a unique image depending on the user's chosen color scheme?

I am attempting to utilize a next/image instead of a traditional img tag in the code snippet below. Using a regular <img> tag, the following code achieves exactly what I desire: <div> <picture> <source srcSet="https://vi ...

An error has occurred in Typescript stating that there is no overload that matches the call for AnyStyledComponent since the update to nextjs

Upgraded to the latest version of nextjs, 13.3.1, and encountered an error in the IDE related to a styled component: Received error TS2769 after the upgrade: No overload matches this call. Overload 1 of 2, '(component: AnyStyledComponent): ThemedSty ...

Issue [ERR_PACKAGE_PATH_NOT_EXPORTED]: The subpath package './lib/parser' is not specified in the "exports" section of the /usr/app/node_modules/postcss/package.json file

After running a docker-compose up command to build my project, I encountered an error: node:internal/errors:464 ErrorCaptureStackTrace(err); ^ Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './lib/parser' is not defined by "expor ...

Obtaining information upon the loading of a Modal in a Next.js application

I am currently developing a feature for my application that allows users to add a new project to a timesheet system. To achieve this, I have created a Modal with a form inside. The form includes a Select field that should display all existing user names f ...

What is the best way to display an image along with a description using Firebase and next.js?

I am currently utilizing Firebase 9 and Next.js 13 to develop a CRUD application. I am facing an issue where the images associated with a post are not correctly linked to the post ID. Furthermore, I need guidance on how to display these images in other com ...

When utilizing Tailwind and DaisyUI within a Next.js application, I am facing difficulties in getting the navigation bar to extend across the entire webpage

I recently encountered an issue with my next.js app that utilizes DaisyUI, a tailwind-based CSS component library. The problem I'm facing is that no matter what I do, the DaisyUI navbar refuses to stretch all the way across the webpage horizontally. I ...

Problem with Next.js router language settings

I have configured different locales for our application including uk and us. For the blog section, we can use either us/blog or just /blog for the uk locale. After switching to the us locale like this: (locale = "us") const updateRoute = (locale ...