首页 文章

为非根路径构建聚合物应用程序

提问于
浏览
1

我认为这不是Serving Polymer App to a /path not at root的重复,因为它是关于更新版本的Polymer-cli 1.8版和Polymer 3

我创造了一个非常简单的组件,当从根路径服务时,它与“聚合物服务”和“聚合物构建”一起使用 .

根据文档,您可以使用--base-path构建选项为非根路径构建应用程序 . 但是,这似乎并不适用于所有资源

示例项目在github上https://github.com/anneb/polymer-simple-component/

基础:

的index.html

<!doctype html>
<html lang="en">
  <head>
    <title>Simple Polymer app</title>
    <base href="/">
  </head>
  <body>
    <script src="node_modules/@webcomponents/webcomponentsjs/webcomponents-loader.js"></script>    
    <script type="module" src="src/components/simple-component.js"></script>
    <simple-component></simple-component>
  </body>
</html>

相对引用的简单组件../../ images/spinner.gif:

import {LitElement, html} from '@polymer/lit-element';
class SimpleComponent extends LitElement {
  _render() {
    return html`<div><img src="../../images/spinner.gif" alt="Spinner"></div>`;
  }
}
customElements.define('simple-component', SimpleComponent);

以上工作(微调器可见)如果测试

polymer serve

polymer build

但是,当构建时:

polymer build --name es5-bundled --base-path es5-bundled

您现在可以从构建目录(build / es5-bundled的父代)中提供es5-bundled,现在代码主要使用path / es5-bundled /,但仍然需要在/images/spinner.gif中引用spinner.gif,为什么?

我的polymer.json:

{
    "entrypoint": "index.html",
    "shell": "src/components/simple-component.js",
    "sources": [
      "images/**/*"
    ],
    "extraDependencies": [
      "node_modules/@webcomponents/webcomponentsjs/**"
    ],
    "builds": [
      {
        "name": "es5-bundled",
        "js": {
          "compile": "es5",
          "minify": true,
          "transformModulesToAmd": true
        },
        "css": {
          "minify": true
        },
        "html": {
          "minify": true
        },
        "bundle": true,
        "addServiceWorker": true
      }
    ],
    "moduleResolution": "node",
    "npm": true
}

1 回答

  • 0

    示例组件使用相对路径:

    return html`<div><img src="../../images/spinner.gif" alt="Spinner"></div>`;
    

    使用 import.meta.url 中的模块URL可以改进这一点,如下所示:

    return html`<div>
      <img src$="${new URL('../../images/spinner.gif', import.meta.url).href}" alt="Spinner">
      </div>`;
    

    由于例如Firefox不支持 import.meta.url ,您必须使用选项--js-transform-import-meta polymer build

    polymer build --name es5-bundled --build-path es5-bundled --js-transform-import-meta
    

    适用于单页应用的 import.meta.url 的另一种解决方法是:

    return html`<div>
      <img src$="${this.baseURI}/images/spinner.gif" alt="Spinner">
      </div>`;
    

相关问题