背景
在umi项目中引用html文件,使用html-loader
解析html文件(,)
"dumi": "^1.1.0"
"html-loader": "^3.1.0"
环境信息
tiands@tiandsdeMacBook-Pro demo-doc % node -v
v14.18.1
tiands@tiandsdeMacBook-Pro demo-doc % npm -v
6.14.15
问题描述
通过umi配置项chainWebpack添加了html-loader
,运行项目的终端报错TypeError: this.getOptions is not a function
umirc.ts
配置
import { defineConfig } from 'dumi';
export default defineConfig({
title: 'demo文档',
...
chainWebpack(config){
config.module
.rule('html-loader')
.test(/\.html$/)
.exclude
.end()
.use('html-loader')
.loader('html-loader');
},
...
});
react组件代码
import React from 'react';
import styles from './EchartsMap.less';
import data from './中国地图.html';
export interface EchartsMapProps extends React.HTMLAttributes<HTMLDivElement> {}
const EchartsMap = (props: EchartsMapProps) => {
const { className = '', ...otherProps } = props;
return (
<div className={`${styles.root} ${className}`} {...otherProps}>
<iframe
title="resg"
srcDoc={data}
style={{ width: '100%', border: '0px', height: '600px' }}
sandbox="allow-same-origin allow-scripts allow-popups allow-forms"
scrolling="auto"
/>
</div>
);
};
export default EchartsMap;
报错信息
ERROR Failed to compile with 1 errors 下午4:14:24
error in ./src/PureHtml/ components/EchartsMap/中国地图.html
Module build failed (from ./node_modules/html-loader/dist/cjs.js):
TypeError: this.getOptions is not a function
at Object.loader (/Users/tiands/Desktop/github/demo-doc/node_modules/html-loader/dist/index.js:23:27)
@ ./src/PureHtml/ components/EchartsMap/EchartsMap.tsx 6:0-31 24:12-16
@ ./src/.umi/dumi/demos/index.ts
@ ./src/.umi/dumi/layout.tsx
解决流程
- 大致看下报错,一个方法没找到,没什么头绪,
- 搜索“umi htm-loderl this.getOptions is not a function”,找到一片文章TypeError: this.getOptions is not a function(html-loader),文章说是
html-loader
版本太高,报错很一致,但是他是vue项目
- 搜索“html-loader this.getOptions is not a function”,找到一篇
TypeError: this.getOptions is not a function #378 - GitHub
的webpack相关文章,里面说html-loader@2.0
不支持webpack5
原因分析
umi项目默认使用webpack4(umi-文档)
html-loader
从2.0开始就仅支持webpack5(html-loader/releases)
解决方案
方案一:降级html-loader
先移除之前的版本
npm uninstall html-loader
安装较稳定版本
npm i html-loader@1.3.0 --save
方案二:使用webpack5编译项目
修改umirc.ts
配置项webpack5
import { defineConfig } from 'dumi';
export default defineConfig({
title: 'demo文档',
...
chainWebpack(config){
config.module
.rule('html-loader')
.test(/\.html$/)
.exclude
.end()
.use('html-loader')
.loader('html-loader');
},
webpack5:{},
...
});