简体   繁体   English

如何将 html 文件作为字符串导入反应?

[英]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.我有一个 HTML 模板作为单独的文件,我想将其导入到我的反应应用程序中。 The intention will be replacing specific keywords and then sending it as the body in an email.目的是替换特定的关键字,然后将其作为正文发送到 email 中。

How can I import this html file into my react application?如何将此 html 文件导入我的反应应用程序?

I have tried import htmlString from '../../../constants/EmailHTML.html';我试过import htmlString from '../../../constants/EmailHTML.html'; as well as var html = require('../../../constants/EmailHTML.html');以及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.模块解析失败:意外令牌 (1:0) 您可能需要适当的加载器来处理此文件类型,目前没有配置加载器来处理此文件。

Effectively this question boils down to: How do I import a text file as a string in React?实际上,这个问题归结为:如何在 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.这是一个经常回答的问题,所有结果似乎都是使用异步加载器——考虑到文件在我的 src 目录中,在构建之前准备好 go ,因此实际上不需要发生这种情况。

Answer for create-react-app: create-react-app 的答案:

  • Install the raw-loader package npm i --save raw-loader安装raw-loader package npm i --save raw-loader
  • Add a test HTML file you want read to src.将要读取的测试 HTML 文件添加到 src。 I added test.html.我添加了 test.html。
  • Add the lines below where you want to get the contents of the HTML file into a JavaScript string.将下面要获取 HTML 文件内容的行添加到 JavaScript 字符串中。 html will contain the string contents of the file. html将包含文件的字符串内容。

Code:代码:

// eslint-disable-next-line import/no-webpack-loader-syntax
var htmlModule = require('raw-loader!./test.html');
var html = htmlModule.default;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM