javascript - 尝试导入 HTML 文件时的 Typescript 错误
我正在尝试导入一个 HTML 文件,以便在 React 组件内渲染它。
我收到以下 TypeScript 错误:
Cannot find module './privacy_policy.html' or its corresponding type declarations.ts(2307)
除了使用 @ts-ignore,我还能做些什么来摆脱它?
答案#1
你可以考虑在项目中名为 custom.d.ts 的文件中声明一个 *.html 模块(在你定义 tsconfig.json 的同一位置)。
例如,我在一个网络应用程序(本质上是 Vanilla JS + 新代码的 TS)中使用了这个配置,该应用程序使用 webpack 打包,用于处理不同于 JS(x) 或 TS(x) 的文件类型的导入。
正如你所说,另一种方法是在只针对单个特定需求时使用 @ts-ignore 方法。
关于这种方法的备注:在我的情况下,TypeScript 的转译是通过 webpack(使用 babel-loader)处理的,导入同样是通过 webpack 处理的(通过特定的加载器,对于 HTML 是 html-loader)。
html-loader 让你可以像在 TypeScript/JavaScript 文件中导入字符串一样导入 HTML 文件。
通常,如果你使用 ReactApp 模板,你应该在构建流水线中包含 html-loader(它在后台运行 webpack),所以你应该可以使用它。
这是我的 custom.d.ts 文件的样子:
/*
* Tells the IntelliSense to allow import of the following file extensions in TypeScript.
* Current Webpack config for these files doesn't embed their content, but provides the file path inside the Webpack bundle.
*/
declare module "*.svg" {
const content: string;
export default content;
}
declare module "*.png" {
const content: string;
export default content;
}
declare module "*.html" {
const content: string;
export default content;
}
答案#2
你必须将你的 HTML 代码转换为 JSX(如果你使用 Typescript,则转换为 TSX)。在网上查找,有一些工具可能会帮助你!
然后你将能够把你的 HTML(转换为 JSX)导入到你的脚本中:
import PrivacyPolicy from 'privacy-policy.jsx'
return (
<PrivacyPolicy />
)
