Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import html file into react as string?

I have an HTML template as a separate file that I would like to import into my react application. The intention will be replacing specific keywords and then sending it as the body in an email.

How can I import this html file into my react application?

I have tried import htmlString from '../../../constants/EmailHTML.html'; as well as var html = require('../../../constants/EmailHTML.html'); (which was suggested in this similar question)

I get the following error for both attempts:

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.

Effectively this question boils down to: How do I import a text file as a string in React? This is an often-answered question and all the results seem to be to use an async loader -- something that shouldn't really need to happen given the file is in my src directory ready to go before build.

like image 305
lowcrawler Avatar asked Jul 20 '26 17:07

lowcrawler


1 Answers

Answer for create-react-app:

  • Install the raw-loader package npm i --save raw-loader
  • Add a test HTML file you want read to src. I added test.html.
  • Add the lines below where you want to get the contents of the HTML file into a JavaScript string. html will contain the string contents of the file.

Code:

// eslint-disable-next-line import/no-webpack-loader-syntax
var htmlModule = require('raw-loader!./test.html');
var html = htmlModule.default;
like image 192
Rich N Avatar answered Jul 22 '26 07:07

Rich N