NextJS 13 + React项目添加await调用后出现loader配置错误求助
我的代码如下:
import getCurrentUser from '@/app/actions/getCurrentUser'; const EmptyState = async () => { const currentUser = await getCurrentUser(); let divClassName = `px-4 py-10 sm:px-6 lg:px-8 lg:py-6 h-full flex justify-center items-center`; let h3ClassName = `mt-2 text-2xl font-semibold`; if (currentUser?.isDarkTheme) { divClassName += ` bg-gray-800`; h3ClassName += ` text-gray-100`; } else { divClassName += ` bg-gray-100`; h3ClassName += ` text-gray-800`; } return ( <div className={divClassName}> <div className="text-center items-center flex flex-col"> <h3 className={h3ClassName}> Welcome to ChitChat </h3> </div> </div> ); } export default EmptyState;
添加const currentUser = await getCurrentUser();后出现以下错误:
./node_modules/@mapbox/node-pre-gyp/lib/util/nw-pre-gyp/index.html
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.
我试过安装babel-preset-es2015没用,加"use client"也会触发错误,求解决办法。
这问题是因为@mapbox/node-pre-gyp包里的HTML文件没被Webpack正确处理,大概率是你项目里某个依赖(比如带原生编译的库,像sqlite3、sharp这类)间接引入了这个包,而Next.js默认的Webpack配置没包含处理HTML文件的loader。给你几个可行方案:
排查并替换依赖:先检查
getCurrentUser里用到的库,看看哪个依赖拉取了@mapbox/node-pre-gyp。如果可以的话,换成不需要原生编译的替代方案,比如用纯JS的库替代带原生编译的依赖。配置Webpack处理HTML文件:在项目根目录的
next.config.js中添加Webpack配置,用file-loader处理HTML文件:
/** @type {import('next').NextConfig} */ const nextConfig = { webpack: (config) => { config.module.rules.push({ test: /\.html$/, use: ['file-loader'], }); return config; }, }; module.exports = nextConfig;
配置完成后重启开发服务器试试。
清理依赖缓存:删除
node_modules文件夹、package-lock.json(或yarn.lock),然后重新执行npm install(或yarn install),有时候依赖缓存异常会导致这类问题。忽略无用的HTML文件:如果这个
index.html对你的项目没用,可以用null-loader忽略它:- 先安装依赖:
npm install null-loader --save-dev - 修改
next.config.js:
- 先安装依赖:
/** @type {import('next').NextConfig} */ const nextConfig = { webpack: (config) => { config.module.rules.push({ test: /nw-pre-gyp\/index\.html$/, use: ['null-loader'], }); return config; }, }; module.exports = nextConfig;
内容的提问来源于stack exchange,提问作者Ibanez33

