NextJS跳转注册页触发Fast Refresh全量刷新及脚本加载失败问题
Next.js 跳转注册页时的脚本加载/全量刷新问题
问题现象
使用<Link href="/register">Register</Link>跳转注册页面时,点击会触发两种异常之一:
- NextJS加载脚本失败
- Fast Refresh执行全量刷新
两种情况的终端提示信息一致,且已排查出问题源于组件中className={styles.<xxx>}的SCSS模块使用方式,但不清楚正确的使用方法。
相关代码
注册页组件
import type { NextPage } from "next/types"; import type { FormEvent } from "react"; import { useRef } from "react"; import { createUser } from "../../helpers/helperFuncs"; import styles from "./styles.module.scss"; const Register: NextPage = (): JSX.Element => { const emailInputRef = useRef<HTMLInputElement | null>(null); const passwordInputRef = useRef<HTMLInputElement | null>(null); const submitHandler = async (event: FormEvent<HTMLFormElement>) => { event.preventDefault(); const enteredEmail = emailInputRef.current?.value ?? ""; const enteredPassword = passwordInputRef.current?.value ?? ""; // 创建新用户 try { const createdUser = await createUser(enteredEmail, enteredPassword); console.log("createdUser", createdUser); } catch (err) { console.log("err", err); } }; return ( <div className={styles.auth}> <h1>Sign Up</h1> <form onSubmit={submitHandler}> <div className={styles.control}> <label htmlFor="email">Your Email</label> <input type="email" id="email" required ref={emailInputRef} /> </div> <div className={styles.control}> <label htmlFor="password">Your Password</label> <input type="password" id="password" required ref={passwordInputRef} /> </div> <div className={styles.actions}> <button>Create Account</button> </div> </form> </div> ); }; export default Register;
createUser函数
async function createUser(email: string, password: string) { const response = await fetch("/api/auth/register", { method: "POST", body: JSON.stringify({ email, password }), headers: { "Content-Type": "application/json", }, }); const data = await response.json(); if (!response.ok) { throw new Error(data.message || "Something went wrong"); } return data; } export { createUser };
解决方法
1. 确认SCSS模块基础配置
Next.js 默认支持.module.scss,只需确保:
- 样式文件名严格为
[name].module.scss(你的styles.module.scss符合要求) - 导入方式为默认导入:
import styles from "./styles.module.scss";(代码中已正确实现)
2. 修复Fast Refresh全量刷新
- 重启开发服务器:缓存异常是常见诱因,关闭服务器后重新执行
npm run dev - 检查SCSS语法:确保
styles.module.scss中没有语法错误(比如未闭合的嵌套、无效属性),语法错误会导致模块编译失败触发全量刷新 - 禁止修改styles对象:不要在组件中直接修改
styles对象(如styles.auth = "new-class"),这会破坏模块的不可变性,导致热更新失效
3. 解决脚本加载失败
- 清理缓存并重装依赖:
rm -rf .next node_modules/.cache npm install npm run dev
- 确认安装sass依赖:Next.js需要
sass编译SCSS,未安装则执行:
npm install sass --save-dev
4. 额外排查方向
- 检查
next.config.js中的Webpack自定义配置,错误配置可能导致SCSS模块编译异常 - 排查
helperFuncs等依赖模块是否存在副作用代码(如模块顶层执行DOM操作、修改全局变量),这类代码会触发Fast Refresh全量刷新
内容的提问来源于stack exchange,提问作者Blitva
相关产品推荐
相关产品推荐

