Is it possible to transform a webpack configuration into a Next.js configuration?

i have come across a webpack configuration setup from https://github.com/shellscape/webpack-plugin-serve/blob/master/recipes/watch-static-content.md:

const sane = require('sane');
const { WebpackPluginServe: Serve } = require('webpack-plugin-serve');

const serve = new Serve({ static: ['/app/assets'] });
const watcher = sane('/app/assets', { glob: [ '**/*.md' ] });

serve.on('listening', () => {
  watcher.on('change', (filePath, root, stat) => {
    console.log('file changed', filePath);
  });
});

serve.on('close', () => watcher.close());

module.exports = {
  mode: 'development',
  plugins: [serve],
  watch: true
};

i'm attempting to convert this into a next.config.js file but running into an error:

TypeError: config.push is not a function

const sane = require('sane')
const { WebpackPluginServe: Serve } = require('webpack-plugin-serve')

const serve = new Serve({ static: ['./styles'] })
const watcher = sane('./styles', { glob: ['**/*.css'] })

serve.on('listening', () => {
  watcher.on('change', (filePath, root, stat) => {
    console.log('file changed', filePath)
  })
})

serve.on('close', () => watcher.close())

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  swcMinify: true,
  rewrites: async () => {
    return [
      {
        source: '/',
        destination: '/index.html',
      },
    ]
  },
  webpack: (config, options) => {
    config.plugins.push(serve)
    config.push({
      mode: 'development',
      watch: true,
    })
    return config
  },
}

module.exports = nextConfig

what would be the correct way to make this conversion?

Answer №1

successfully discovered a solution.

const webpack = require('webpack')
const { merge } = require('webpack-merge')
const sane = require('sane')
const { WebpackPluginServe: Serve } = require('webpack-plugin-serve')

const serve = new Serve({ static: ['./styles'] })
const watcher = sane('./styles', { glob: ['**/*.css'] })

serve.on('listening', () => {
  watcher.on('change', (filePath, root, stat) => {
    console.log('file changed', filePath)
  })
})

serve.on('close', () => watcher.close())

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  swcMinify: true,
  rewrites: async () => {
    return [
      {
        source: '/',
        destination: '/index.html',
      },
    ]
  },
  webpack: (oldConfig, options) => {
    const plugins = oldConfig.plugins.filter((plugin) => {
      if (
        plugin.constructor &&
        plugin.constructor.name === 'HotModuleReplacementPlugin'
      )
        return false
      return plugin
    })

    oldConfig.plugins = plugins

    const config = {
      mode: 'development',
      watch: true,
      plugins: plugins.concat([serve]),
    }
    return merge(oldConfig, config)
  },
}

module.exports = nextConfig

encountering some new errors at the moment:

⬢ wps: Warning The value of publicPath was not found on the filesystem in any static paths specified

(node:24455) [DEP_WEBPACK_WATCH_WITHOUT_CALLBACK] DeprecationWarning: A 'callback' argument needs to be provided to the 'webpack(options, callback)' function when the 'watch' option is set. There is no way to handle the 'watch' option without a callback.

despite the errors, the conversion process is functioning effectively!

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 with sending images using Node-gcm and Nodejs

My current project involves an Ionic app that communicates effectively with a Node.js server. The app serves as a notification system utilizing node-gcm, but I have encountered an issue - gcm does not support sending images directly due to payload size lim ...

The rc-form package in npm is issuing a Warning for the getFieldDecorator method when `defaultValue` is not being used as an option

Currently, I am on the rc-form 2.4.8 version and I am utilizing the getFieldDecorator method in my codebase. However, an issue has arisen: Warning: defaultValue is not a valid property for getFieldDecorator; the correct use is to set value, so please uti ...

Custom directives are designed to receive arrays as string inputs

I've encountered an issue with my custom directive that has an isolated scope. When I pass an Array variable to the directive, it is being treated as a String inside the directive. This is how my directive looks: angular.module('my.directives& ...

Implementing effective session management for storing cart items in Next.js

I've been searching for a way to effectively store products added to the cart in the session. Here's my current approach: page.tsx const ProductPage = () => { const { product, loading, error } = useProductData(); const { cart, addToCart: ...

npm fails to function properly following the execution of the 'npm install' command

After downloading and installing node.js + npm from https://nodejs.org/en/, I created a project folder and navigated into it on Windows 10. However, when I attempted to run the command: C:\nodejs\demo>npm install <a href="/cdn-cgi/l/email- ...

An error has occurred: Expected a string as the element type in React when attempting to update the state

I encountered an issue while trying to update the state after fetching data. Error: Element type is invalid - expected a string (for built-in components) or a class/function (for composite components), but received: undefined. This could be due to forgett ...

Navigating through nested routes in Express.js and extracting parameters may seem daunting at first, but

In my routing setup, I have defined it as shown below: export const router = Router(); const appRoutes = [ { path: "/", router: usersRouter, }, { path: "/games/", router: gamesRouter, }, { path: "/gam ...

Tips on transmitting form information from client-side JavaScript to server-side JavaScript with Node.js

Having created an HTML page with a form, my goal is to capture user input and store it in a JSON file. However, I've run into some confusion... In the process, I utilized the express module to set up a server. My mind is juggling concepts such as AJA ...

Mocking objects in unit test cases to simulate real-life scenarios and test the

How do I pass a mocked event object and ensure it is validated? onCallFunction() { const eventValue = event; if (!eventValue.relatedTarget || !eventValue.relatedTarget.last.contain('value')) { super.onCallFuncti ...

I'm still searching for a proper solution on how to access JavaScript/jQuery functions within Colorbox

For my website, I am utilizing PHP, jQuery/JavaScript, Colorbox (a jQuery lightbox plugin), Smarty, and other tools. Currently, I am working on displaying data in a popup using the Colorbox plugin. However, I am facing an issue with calling a JavaScript fu ...

What is the best way to retrieve a response from a PHP file as an array through Ajax?

Seeking assistance in retrieving a complete address by entering the postal code in an HTML form textbox and clicking a button. The setup involves two files - one containing the ajax function and the other housing the PHP code. Uncertainty looms over whethe ...

The only thing you can see in MongoDB output is the objectid

Trying to save data in mongodb using an open schema. After making a post request, the only thing showing up in the database is the objectid. As someone new to MongoDB and Node.js, I'm struggling to identify where my mistake lies. // <---------se ...

Guide to Including an Object in AngularJS Scope

I am completely new to Angular JS and mongod. My goal is to add a new ingredient field to this page for the specific drink that the + button is clicked on. Here is how my view looks like: UI Image This is what my .jade file contains: block content ...

Sending information to a jQuery UI Dialog

I'm currently working on an ASP.Net MVC website where I display booking information from a database query in a table. Each row includes an ActionLink to cancel the booking based on its unique BookingId. Here's an example of how it looks: My book ...

Exploring the possibilities of using AngularJS for AJAX functionality in a Ruby On Rails

I recently started learning AngularJS and Rails, and I attempted to develop a Rails application incorporating AngularJS. Currently, I am looking to make a POST request to send data and insert it into the database. In the Activity Controller: def create ...

transmitting an array from JavaScript to PHP

Struggling with passing an array from JavaScript to PHP for a school assignment. I'm still learning and can't seem to figure out what's missing. Any help would be greatly appreciated. This is the code I've tried: if(bets.length > ...

javascript / php - modify input fields according to selection change

Can anyone help me with an issue I'm facing? I want to update multiple textfields whenever a new option is selected from my dropdown menu. I've written the following code, but it's not working as expected. Can someone figure out what's ...

Issue with calling function from props in React is not being resolved

There seems to be an issue with the function not being called when passed into a functional component. While the onSubmit function is triggered, the login(email, password) function inside the Login component is never executed. Despite placing console.log s ...

Next.js encounters an issue: "The text content does not align with the server-rendered HTML"

I just set up a new Next.js project and added a very basic component: const IdPanel = () => { const [id] = useState(`${Math.random()}`); return ( <div> <h1 id={id} className={id}> {id} </h1> </div> ...

In a Javascript scenario, only the initial button can successfully submit to an Ajax form even when having unique

Similar issues have been reported by other users when looping rows of buttons, often due to inadvertently reusing the same Id or value. I am facing a similar issue, but each of my buttons is unique. AJAX request <script> $(document ...