如何将监听静态资源的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:
modeis set based on your environment (developmentfornext dev,productionfornext build)watchis already enabled by default in development mode
You don't need to manually override these.
Step-by-step fixes
- Remove the invalid
config.pushline: This is the root cause of your error, and those settings are redundant anyway. - Scope the plugin to development mode: There's no need to load
webpack-plugin-serveor run the file watcher in production builds. - 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-serveorsanefor 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
相关产品推荐
相关产品推荐

