将带提取功能的本地 HTML 页面导入另一个 HTML 页面
Importing local HTML page with fetch into another HTML page
基本上,我有一个名为 panel
的 html 文件,其中包含我想插入到另一个主 HTML 文件中的简单 DIV。
我不想使用 Web 组件,而是想实现一个简单的解决方案,如 this answer 中所述。
所以,这是我正在做的测试(只是将面板记录到控制台):
panel.html
<div id="panel">
<h1>It works...</h1>
</div>
get-template.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);})
控制台记录 "null"。
如果此信息有任何不同,我正在使用 parcel-bundler 构建应用程序。
实际问题是由 @CBroe 确定的,是关于当 parcel
构建我的应用程序时,我的 panel.html
资源的文件路径更改为相对于构建的 dist
文件夹。
澄清一下:
- 构建路径之前是相对于
main.ts
文件
- 构建后路径是相对于
dist
文件夹
所以解决办法就是考虑一下panel.html
最后的URL,在用parcel建房前提前参考一下。
像这样的方法适用于我的情况:
main.ts(新)
import { getTemplate } from './get-template'
getTemplate('./panel.html','#panel').then((panel) => {console.log(panel);})
当然,另一步是将实际的 panel.hml
文件复制到 dist
目录中,否则 URL 将指向一个不存在的文件。
我看到有一个 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
。
基本上,我有一个名为 panel
的 html 文件,其中包含我想插入到另一个主 HTML 文件中的简单 DIV。
我不想使用 Web 组件,而是想实现一个简单的解决方案,如 this answer 中所述。
所以,这是我正在做的测试(只是将面板记录到控制台):
panel.html
<div id="panel">
<h1>It works...</h1>
</div>
get-template.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);})
控制台记录 "null"。
如果此信息有任何不同,我正在使用 parcel-bundler 构建应用程序。
实际问题是由 @CBroe 确定的,是关于当 parcel
构建我的应用程序时,我的 panel.html
资源的文件路径更改为相对于构建的 dist
文件夹。
澄清一下:
- 构建路径之前是相对于
main.ts
文件 - 构建后路径是相对于
dist
文件夹
所以解决办法就是考虑一下panel.html
最后的URL,在用parcel建房前提前参考一下。
像这样的方法适用于我的情况:
main.ts(新)
import { getTemplate } from './get-template'
getTemplate('./panel.html','#panel').then((panel) => {console.log(panel);})
当然,另一步是将实际的 panel.hml
文件复制到 dist
目录中,否则 URL 将指向一个不存在的文件。
我看到有一个 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
。