I'm trying to import an HTML file to render it inside of a react component.
I'm getting the following typescript error:
Cannot find module './privacy_policy.html' or its corresponding type declarations.ts(2307)
What could I do to get rid of it (other then use @ts-ignore
)?
You have to transform your HTML code to JSX (or TSX if you are using Typescript). Check online, there are few tools that might help you !
Then you will be able to import your HTML (converted to JSX) into your script:
import PrivacyPolicy from 'privacy-policy.jsx'
return (
<PrivacyPolicy />
)
You can consider declaring a *.html module in a file named custom.d.ts
in your project (at the same place where you defined your tsconfig.json
).
For example, I've used this configuration on a web application (essentially Vanilla JS + TS for newer code) bundled with webpack, to handle import of types of file different from JS(x) or TS(x).
The alternative, as you said, is to use @ts-ignore
approach when it's for a single specific need.
Note for this approach: in my case, the TypeScript transpilation is handled via webpack (with the babel-loader
), and the imports as well are handled via webpack (via specific loaders, which for HTML is html-loader
).
The html-loader
lets you import a HTML file as it was a string in your TypeScript / JavaScript file.
Normally, if you use the ReactApp template, you should have the html-loader
included in the build pipeline (which runs webpack behind the scene), so you should be able to use it.
Here is how it looks my custom.d.ts
file:
/*
* 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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.