Next.js出现Module parse failed: Unexpected character '�'错误如何解决
报错原因
运行时出现Module parse failed: Unexpected character '�' (1:0)报错,本质是webpack无法识别二进制文件格式,当前配置同时启用了Next.js原生图片处理能力和第三方next-images插件,两者loader规则冲突导致解析失败。
解决方案
- 第一步:二选一清理冗余图片处理配置
- 方案A:使用Next.js原生图片处理能力(推荐)
- 卸载
next-images依赖
npm uninstall next-images # 或 yarn remove next-images- 移除
next.config.js中withImages相关的配置
- 卸载
- 方案B:保留
next-images插件
在nextConfig的images配置项中添加disableStaticImages: true,关闭Next.js原生图片处理能力,避免冲突:images: { loader: 'default', path: imgLoaderUrl, disableStaticImages: true // 新增这一行 },
- 方案A:使用Next.js原生图片处理能力(推荐)
- 第二步:移除无效配置
当前配置中的build.extend字段不属于Next.js的合法配置项,直接删除该代码块即可。 - 第三步:清理缓存重启项目
删除项目根目录下的.next缓存文件夹,再重新启动开发服务。
修正后参考配置(方案A版本)
const withPlugins = require('next-compose-plugins') const CompressionPlugin = require('compression-webpack-plugin') const withBundleAnalyzer = require('@next/bundle-analyzer')({ enabled: process.env.ANALYZE === 'true', }) let prefixUrl = '' let imgLoaderUrl = '' switch (process.env.ENV) { case 'production': prefixUrl = 'https://webstatic.circleslive.com' imgLoaderUrl = 'https://webstatic.circleslive.com' break case 'staging': prefixUrl = 'https://staging-webstatic.circleslive.com' imgLoaderUrl = 'https://staging-webstatic.circleslive.com' break case 'development': prefixUrl = '' imgLoaderUrl = '/_next/image' break default: prefixUrl = '' imgLoaderUrl = '/_next/image' break } const nextConfig = { poweredByHeader: false, trailingSlash: false, compress: true, future: { webpack5: true, }, env: { ENV: process.env.ENV, }, serverRuntimeConfig: { STRIPE_SECRET_KEY: process.env.STRIPE_SECRET_KEY, }, images: { loader: 'default', path: imgLoaderUrl, }, webpack: (config) => { config.optimization.minimize = true config.plugins.push( new CompressionPlugin({ test: /\.js$|\.css$|\.html$/, }), ) return config } } module.exports = withPlugins( [ [withBundleAnalyzer], ], nextConfig, )
内容的提问来源于stack exchange,提问作者Meghna Varma
相关产品推荐
相关产品推荐

