You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将监听静态资源的Webpack配置正确转换为Next.js配置?

Fixing the TypeError: config.push is not a function in your Next.js Webpack config

Let's break down what's going wrong and fix this step by step:

Why you're hitting this error

The config object passed to Next.js's webpack function is not an array — it's a complete Webpack configuration object. Your line config.push({ mode: 'development', watch: true, }) tries to use an array method on an object, which triggers the TypeError.

Plus, Next.js handles some core Webpack settings automatically:

  • mode is set based on your environment (development for next dev, production for next build)
  • watch is already enabled by default in development mode

You don't need to manually override these.

Step-by-step fixes

  1. Remove the invalid config.push line: This is the root cause of your error, and those settings are redundant anyway.
  2. Scope the plugin to development mode: There's no need to load webpack-plugin-serve or run the file watcher in production builds.
  3. Keep the plugin addition logic: Your line config.plugins.push(serve) is valid — we just need to wrap it in a check for development mode.

Corrected next.config.js code

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

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  swcMinify: true,
  rewrites: async () => {
    return [
      { source: '/', destination: '/index.html' }
    ]
  },
  webpack: (config, options) => {
    // Only load the serve plugin and watcher in development
    if (options.dev) {
      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())

      config.plugins.push(serve)
    }

    return config
  },
}

module.exports = nextConfig

Quick additional notes

  • Next.js has built-in hot reloading for CSS files in development mode. You might not even need webpack-plugin-serve or sane for basic CSS changes — this setup is only necessary if you need custom logic when static files modify.
  • If you're using CSS Modules, make sure your files follow Next.js's convention (name them [name].module.css) to avoid issues with scoping.

内容的提问来源于stack exchange,提问作者deadcoder0904

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 13:08:11