Oops! Next.js Scripts encountered an error: Module '../../webpack-runtime.js' cannot be located

Looking to develop an RSS script with Next.js.

To achieve this, I created a script in a subfolder within the root directory called scripts/ and named it build-rss.js

next.config.js

module.exports = {
    webpack: (config, options) => {
        config.module.rules.push({
            test: /\.svg$/,
            issuer: { and: [/\.(js|ts|md)x?$/] },
            use: [
                {
                    loader: '@svgr/webpack',
                    options: {
                        prettier: false,
                        svgo: true,
                        svgoConfig: { plugins: [{ removeViewBox: false }] },
                        titleProp: true,
                    },
                },
            ],
        })

        if (!options.dev && options.isServer) {
            const originalEntry = config.entry

            config.entry = async () => {
                const entries = { ...(await originalEntry()) }
                entries['./scripts/build-rss'] = './scripts/build-rss.js'
                return entries
            }
        }

        if (!options.isServer) {
            config.resolve.fallback.fs = false
        }

        return config
    },
}

Upon trying to run the script with npm run build:development, as specified in package.json:

"scripts": {
    "clean": "rimraf .next",
    "dev": "next dev",
    "export": "next export",
    "start": "next start",
    "lint": "next lint",
    "build:development": "next build && npm run export && npm run rss:development",
    "build": "next build && npm run export && npm run rss",
    "rss:development": "node ./.next/server/scripts/build-rss.js",
    "rss": "node ./.next/serverless/scripts/build-rss.js"
}

An error is thrown:

Error: Cannot find module '../../webpack-runtime.js'

Despite verifying that the file does exist.

This previously worked without issue. Possibly on previous versions when using the same setup for another project.

I have provided a full demonstration of the error at → https://github.com/deadcoder0904/next-script-rss-error

Simply clone the repository, install it, and execute the script npm run build:development in the terminal to encounter the error.

Answer №1

Reflecting on our discussion:

entry: path.join(__dirname, '..', 'path/to/file')

This is how a webpack entry appears. It can also take the form of an array or object:

entry: [
  path.join(__dirname, '..', 'path/to/file'),
  // other entries here
]

You already have access to the complete webpack configuration:

webpack: (config, options)

So why complicate matters with:

const originalEntry = config.entry

config.entry = async () => {
  const entries = { ...(await originalEntry()) }
  entries['./scripts/build-rss'] = './scripts/build-rss.js'
  return entries
}

When you could simply do this instead:

config.entry.push('./scripts/build-rss')
// config.entry['./scripts/build-rss'] = './scripts/build-rss.js'

I am puzzled by your approach, unless there are nuances in how nextjs loads the webpack configuration.

Additionally, using path.join ensures proper file location, especially considering that webpack will execute from its compiled root directory.

In your previous project, you were on nextjs v10 but now you're on v11 which has switched from webpack 4 to 5 - a significant change. Don't assume compatibility based solely on past successes; each project may necessitate unique considerations.

Initially, I assumed webpack would bundle all code into one output file by default unless overridden by nextjs (if that's even possible). Your inclusion of additional scripts left me bewildered as they seemed unnecessary given this context. However, if webpack is configured for code splitting, where each entry generates a separate file, my perspective shifts. In webpack 5 (not sure about 4), code splitting is active in production but not in development, potentially causing issues between these environments.

You might consider revisiting !options.dev - currently it only adds the script in production while you attempt to run it during development.

If nothing else works, reverting back to nextjs v10 could be a temporary solution, though far from ideal.

At this point, I'm stumped for further suggestions.

Answer №2

Are you in need of a solution still? A quick adjustment to the webpack entry like this appears to have resolved the issue at hand.

entries['scripts/build-rss'] = './scripts/build-rss.js';
// switch from entries['./scripts/build-rss']

Answer №3

I encountered a similar issue! After removing the .next Folder and running npm run dev, everything started working for me!

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

Combining package.json commands for launching both an Express server and a Vue app

I recently developed an application using Vue.js and express.js. As of now, I find myself having to open two separate terminal windows in order to run npm run serve in one and npm start in the other. My ultimate goal is to streamline this process and have ...

Pictures failing to load correctly post Next.js compilation and running yarn start

Currently, I am utilizing Amazon S3 as a Content Delivery Network (CDN) for my application. Everything functions properly when running the application using 'yarn dev' with the domain added to the next config. Upon inspecting the src attribute of ...

Is there a way to dynamically replace a section of a link with the current URL using JavaScript or jQuery?

I have a link that appears on multiple pages, and I want to dynamically change part of the link based on the current URL* of the page being visited. (*current URL refers to the web address shown in the browser's address bar) How can I use JavaScript ...

Unable to retrieve the authorization code following the redirection of the URL

Currently, I am tackling the integration of Salesforce with Slack. Unfortunately, my knowledge of javascript and related technologies is limited. Can someone please review the code and identify what might be missing? // Grab express and request modules ...

Trouble encountered with uploading files using Multer

I am facing an issue with uploading images on a website that is built using React. The problem seems to be related to the backend Node.js code. Code: const multer = require("multer"); // Check if the directory exists, if not, create it const di ...

Encountering an issue with Material-UI and Next.js: "TypeError: theme.spacing is not a function

Encountering an issue after modifying _app.js to dynamically generate a material UI theme. I've been following the implementation example provided by the material-ui team at: https://github.com/mui-org/material-ui/tree/master/examples/nextjs. To summ ...

Sending data to API using AngularJS Http Post

Upon clicking "Add new User", a modal pop-up will appear with a form containing a text field and a checkbox. However, upon clicking the create button, the data is not being posted to the API and the modal pop-up remains open without closing. I would like ...

Efficiently retrieving external API data only when there are updates

My goal is to provide my users with data from an external API, but I'm facing the challenge of not knowing when this API will have new data available. How can I best approach this situation using Node.js? I've experimented with setInterval and n ...

Running multiple web applications with different base directories on a single Express server

I am currently working on serving a website that requires different static directories for various routes. When a GET request is sent to the /tools* route, I want to utilize the /dist/toolsApp/ directory as the base directory for my frontend code. If ...

Iterate over JSON dates in JavaScript

Trying to utilize JavaScript in looping through a JSON file containing time periods (start date/time and end date/time) to determine if the current date/time falls within any of these periods. The provided code doesn't seem to be working as expected. ...

Encountering a problem with npm installation when trying to install a dependency module for express

While attempting to install the npm module express-validator, I encountered an error related to one of its dependencies. Does anyone know how to resolve this issue? npm ERR! 404 Not Found npm ERR! 404 npm ERR! 404 'types/express' is not in the ...

Error during Next.js build: Incompatible types - cannot assign type to 'never'

Encountering an error in the console while attempting to build my project: .next/types/app/facebook/page.ts:8:13 Type error: Type 'OmitWithTag<typeof import("D:/projects/abkh24/client/app/facebook/page"), "metadata" | "defa ...

Exploring Next.js 13: Automating Redirects Following Image Creation

In my current project using Next.js 13, I've managed to create a feature where users can generate images based on their input. The image generation is handled by a function called generateImage, which successfully generates and stores the image in the ...

Having trouble cloning the git repository even after updating npm to the latest version

After installing the latest version of node and npm, I encountered an issue when trying to clone a git repository. The error message received was: "'git' is not recognized as an internal or external command, operable program or batch file." E ...

What could be causing the remove attribute API to not function properly only for the "is" attribute?

var divElement = document.createElement("div"); var innerHTMLText = "<div id='issue' is='if'> some content </div>"; divElement.innerHTML = innerHTMLText; document.body.appendChild(divElement); var newDivElement = document.qu ...

What is the best way to reference an Angular constant within a Gulp configuration file?

Is it possible to retrieve an Angular constant within a Gulp file? For example: angular.module('app').constant('env', { url: 'http://localhost:1337/' }); What is the method for accessing this constant inside a function ...

What is the best way to organize a massive file over 10Gb filled with words?

I've been presented with this interview query: You have an input file containing words (which could be a jumble of letters) separated by commas, and the file size is 10 GB or more. Can you devise an algorithm to sort all these words? Keep in min ...

What is the best way to store types in a TypeScript-based React/Next application?

I'm currently in the process of setting up a Next.js page in the following manner const Index: NextPage<PageProps> = (props) => { // additional code... Prior to this, I had defined my PageProps as follows: type PageProps = { pictures: pi ...

Foundation-sites module missing - new project requires installation of Node modules

I recently encountered an issue that has been discussed multiple times here, but unfortunately, I couldn't find a suitable solution. After formatting my disk and installing macOS Monterey, the following software versions were installed: node.js v16. ...

What's the best way to implement a 60-second delay for a callback function within vows?

I recently created some code to connect to an FTP server and retrieve a lengthy directory listing. However, I am experiencing delays of over 40 seconds before receiving a response. Although I have started testing this code, I keep encountering an error me ...