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.

Rich N
  • 8,939
  • 3
  • 26
  • 33
lowcrawler
  • 6,777
  • 9
  • 37
  • 79
  • Does this answer your question? [require file as string](https://stackoverflow.com/questions/12752622/require-file-as-string) – iBug Mar 09 '21 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. – lowcrawler Mar 09 '21 at 16:49

1 Answers1

4

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;
Rich N
  • 8,939
  • 3
  • 26
  • 33
  • Create-React-App kind of hides the webpack stuff from you unless you 'eject' your project. – lowcrawler Mar 09 '21 at 19:58
  • 1
    I've posted an answer for create-react-app. It would have been good to mention it in the original question :-) – Rich N Mar 10 '21 at 17:12