[英]Importing local HTML page with fetch into another HTML page
Basically, I have a html file called panel
containing a simple DIV that I would like to insert into another main HTML file.基本上,我有一个名为
panel
的 html 文件,其中包含一个简单的 DIV,我想将其插入到另一个主 HTML 文件中。
Instead of using web components, I'd like to implement a simple solution as described in this answer .我想实现一个简单的解决方案,而不是使用 web 组件,如本答案中所述。
So, here is what I am doing for testing (just logging the panel to console):所以,这是我正在做的测试(只是将面板记录到控制台):
panel.html面板.html
<div id="panel">
<h1>It works...</h1>
</div>
get-template.ts获取模板.ts
export async function getTemplate(filepath: string, selectors: string) {
let response = await fetch(filepath);
let txt = await response.text();
let html = new DOMParser().parseFromString(txt, 'text/html');
return html.querySelector(selectors);
}
main.ts主文件
import { getTemplate } from './get-template'
getTemplate('/path/to/panel.html','#panel').then((panel) => {console.log(panel);})
The console logs "null".控制台记录“null”。
If this info could make any difference, I am using parcel-bundler to build the application.如果此信息可以产生任何影响,我将使用parcel-bundler 来构建应用程序。
The actual problem was determined by @CBroe and was about the fact that when parcel
builds my application, the file path of my panel.html
resource changes to be relative to the built dist
folder.实际问题是由@CBroe确定的,是关于当
parcel
构建我的应用程序时,我的panel.html
资源的文件路径更改为相对于构建的dist
文件夹的事实。
Just to clarify:只是为了澄清:
main.ts
filemain.ts
文件的dist
folderdist
文件夹的So the solution is to think about the final URL the panel.html
will have, and refer to it in advance before building with parcel.所以解决方案是考虑
panel.html
最终会有的URL,在用parcel构建之前提前参考。
Something like this would work in my case:在我的情况下,这样的事情会起作用:
main.ts (new) main.ts(新)
import { getTemplate } from './get-template'
getTemplate('./panel.html','#panel').then((panel) => {console.log(panel);})
Then of course, the other step will be to copy the actual panel.hml
file into the dist
directory, otherwise the URL will point to a non existing file.那么当然,下一步就是将实际的
panel.hml
文件复制到dist
目录中,否则 URL 将指向一个不存在的文件。
I see there was a github issue about automatically copy static (or assets) files in the parcel repository, and one of the solution provided is to use the plugin parcel-plugin-static-files-copy
.我看到有一个关于在parcel存储库中自动复制静态(或资产)文件的github问题,提供的解决方案之一是使用插件
parcel-plugin-static-files-copy
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.