3

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.

2
  • Does this answer your question? require file as string Commented Mar 9, 2021 at 16:35
  • Not really, as those rely on using the filesystem module from node.js and the use of a readFileSync. Though, perhaps importing is simply a complicated process and I need to deal with it. Commented Mar 9, 2021 at 16:49

1 Answer 1

6

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;
Sign up to request clarification or add additional context in comments.

2 Comments

Create-React-App kind of hides the webpack stuff from you unless you 'eject' your project.
I've posted an answer for create-react-app. It would have been good to mention it in the original question :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.