【问题标题】:ParcelJs: bundle an html file that contains an anchor tag and that is not an entry pointParcelJs:捆绑一个包含锚标记且不是入口点的 html 文件
【发布时间】:2021-12-29 14:35:01
【问题描述】:

我有一个与 Parcel 捆绑的简单 Web 应用程序(无框架)。它有一个pages 文件夹和一个components 文件夹。组件只是我想在整个应用程序中重用的一些 html。页面是包的入口点 (parcel build pages/index.html pages/*/*.html)。 组件由 html 文件和 javascript 文件组成。我使用bundle-text:html 导入到javascript 中,使用字符串结果创建一个DOM 元素,然后将其附加到文档中。然后将 javascript 文件导入到 pages 目录中的文件中。 问题是,如果我在href 指向/pages 中的文件的组件内使用锚标记,则捆绑包被破坏。它无法正确解析路径。如果我使用相对于导入组件的路径,例如。 <a href="/someFolderInPages/index.html> Parcel 找不到正确的文件:@parcel/core: Failed to resolve '/someFolderInPages/index.html' from './components/comp-1/index.html'。 如果我使用从/components/pages 的路径,例如。 <a href="../pages/someFolderInPages/index.html> 它说:Error: Bundles must have unique names。 有没有办法解决这个问题,或者我应该将 html 文件完全放到组件中?

【问题讨论】:

    标签: javascript html parceljs


    【解决方案1】:

    当您从样式为 /someFolderInPages/index.html 的组件中引用页面时,您可能会遇到错误 - 开头的 / 是“绝对说明符”并告诉包裹 to start at the project root。因此,您可能需要编写 /pages/someFolderInPages/index.html/src/pages/someFolderInPages/index.html(取决于您的项目的结构),以便 parcel 能够正确找到所需的源文件。

    但是,这并不能真正解决您的问题,因为您遇到的第二个错误(当您使用样式 "../pages/someFolderInPages/index.html" 时)是您包裹 确实 解决依赖关系时会发生的情况。在我看来,这可能是包裹中的一个错误 - 如果您愿意,请随时提交 github 问题。

    但是,可能有更好的方法来完成您想要的,并且具有避免此错误的副作用。您说“组件只是我想在整个应用程序中重用的 html 的一部分”-如果仅此而已,那么如果在构建时而不是运行时将它们插入到页面中,则对应用程序的用户来说性能会更高-时间。

    Parcel 可以使用 .pug 模板完全做到这一点(请参阅 parcel docspug docs)。

    例如,一个“组件”可能有一些可重用的 html 的 sn-p(用 pug 语法表示):

    /src/components/someComponent.pug

    a(href="../pages/someFolderInPages/index.pug") Link from a component to a page
    

    然后,您可以像这样包含在“页面”中:

    /src/page/anotherFolderInPages/index.pug

    doctype html
    html
      body
        h1 The link from the component will show up below:
        include ../../components/someComponent.pug
    

    Parcel 将负责在编译时构建页面(将其转换为 .html 文件),因此无需在运行时下载和执行单独的 javascript 包来插入一些 HTML。

    【讨论】:

      猜你喜欢
      • 2019-06-27
      • 2022-01-06
      • 2012-10-28
      • 2018-11-22
      • 2016-01-26
      • 2015-06-12
      • 1970-01-01
      • 2020-06-08
      • 2017-08-15
      相关资源
      最近更新 更多