Next.js中使用html-loader加载HTML文件报错的解决咨询
解决Next.js中html-loader加载HTML文件失败的问题
问题现象
加载HTML文件时出现以下解析错误:
Module parse failed: Unexpected token (2:2) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
现有配置与代码
next.config.js
/** @type {import('next').NextConfig} */ const nextConfig = { reactStrictMode: true, swcMinify: true, env: { SERVICE_ID: process.env.SERVICE_ID, }, webpack: { test: /\.(html)$/, use: { loader: "html-loader", options: { attrs: [":data-src"], }, }, }, }; module.exports = nextConfig;
Planning.jsx组件
import Page from "../planning.html"; const Planning = () => { let htmlDoc = { __html: Page }; return <div dangerouslySetInnerHTML={htmlDoc} />; }; export default Planning;
planning.html文件
<div id="ID" data-id-projet="ID" > Loading... </div> <script type="text/javascript" src="https://reservation.elloha.com/Scripts/widget-loader.min.js?v=38" ></script> <script type="text/javascript"> var constellationWidgetUrlID = "https://reservation.elloha.com/Widget/BookingCalendar/ID"; constellationTypeModuleID = 2; constellationBookingCalendarLoad( "ID" ); </script>
解决方案
1. 修正webpack配置写法
Next.js的webpack配置需要以函数形式修改原有配置,而非直接添加规则。更新next.config.js:
/** @type {import('next').NextConfig} */ const nextConfig = { reactStrictMode: true, swcMinify: true, env: { SERVICE_ID: process.env.SERVICE_ID, }, webpack: (config, { isServer }) => { // 新增html-loader规则 config.module.rules.push({ test: /\.html$/, use: { loader: "html-loader", options: { attrs: [":data-src"], }, }, }); return config; }, }; module.exports = nextConfig;
2. 手动处理HTML中的脚本执行
dangerouslySetInnerHTML不会自动执行内嵌的<script>标签,需要手动创建脚本并执行逻辑。更新Planning.jsx:
import { useEffect, useState } from 'react'; import Page from "../planning.html"; const Planning = () => { const [htmlContent, setHtmlContent] = useState(Page); useEffect(() => { // 加载外部脚本 const externalScript = document.createElement('script'); externalScript.src = 'https://reservation.elloha.com/Scripts/widget-loader.min.js?v=38'; externalScript.type = 'text/javascript'; document.body.appendChild(externalScript); // 配置全局变量 window.constellationWidgetUrlID = "https://reservation.elloha.com/Widget/BookingCalendar/ID"; window.constellationTypeModuleID = 2; // 外部脚本加载完成后执行初始化函数 externalScript.onload = () => { window.constellationBookingCalendarLoad?.("ID"); }; // 组件卸载时清理资源 return () => { document.body.removeChild(externalScript); delete window.constellationWidgetUrlID; delete window.constellationTypeModuleID; }; }, []); return <div dangerouslySetInnerHTML={{ __html: htmlContent }} />; }; export default Planning;
3. 确保安装html-loader
如果未安装依赖,执行以下命令:
npm install html-loader --save-dev # 或使用yarn yarn add html-loader --dev
内容的提问来源于stack exchange,提问作者SanB
相关产品推荐
相关产品推荐

