Next.js 12/13是否支持CDN JS的SRI?配置报错求助
Next.js 12配置SRI时遭遇"SriPlugin不是构造函数"错误及版本支持确认
问题背景
使用Next.js 12版本,为实现子资源完整性(SRI)配置webpack-subresource-integrity插件时,触发了"SriPlugin不是构造函数"的错误,配置代码如下:
const withOffline = require('next-offline'); const withPlugins = require('next-compose-plugins'); const CompressionPlugin = require('compression-webpack-plugin'); const SriPlugin = require('webpack-subresource-integrity'); let nextConfig = {}; const customConfig = { webpack: (config, { isServer, dev }) => { config.output.crossOriginLoading = 'anonymous'; config.plugins.push( new SriPlugin({ hashFuncNames: ['sha256', 'sha384'], enabled: true, }) ); return config; }, }; nextConfig = { ...customConfig, }; module.exports = withPlugins([[withOffline, { scope: '/' }], [{ compress: true }]], nextConfig);
同时需要确认Next.js 12和13是否支持SRI。
错误排查与修复
1. 核心问题:模块导出方式不匹配
webpack-subresource-integrity从v5版本开始采用ES模块默认导出,而Next.js 12的next.config.js使用CommonJS规范,直接require导入会拿到模块对象而非构造函数,导致报错。
修复方法:
修改导入语句,显式获取default导出:
const SriPlugin = require('webpack-subresource-integrity').default;
2. 额外优化建议
- 开发环境禁用SRI:热重载场景下SRI哈希会频繁变化,引发资源加载错误,建议仅在生产环境启用:
new SriPlugin({ hashFuncNames: ['sha256', 'sha384'], enabled: !dev, // 仅生产环境启用 }) - 服务器端跳过插件:服务器端构建不需要生成前端资源的SRI哈希,避免不必要的性能开销:
if (!isServer && !dev) { config.plugins.push( new SriPlugin({ hashFuncNames: ['sha256', 'sha384'], enabled: true, }) ); }
Next.js版本对SRI的支持情况
- Next.js 12:官方未内置SRI支持,需通过
webpack-subresource-integrity插件手动配置,上述修复后可正常工作。 - Next.js 13:无论Pages Router还是App Router模式,官方仍未内置SRI支持,但同样可以通过webpack插件实现配置。注意App Router模式下webpack配置写法略有不同,需确保插件在客户端构建中生效。
内容的提问来源于stack exchange,提问作者Sarada
相关产品推荐
相关产品推荐

