【问题标题】:Build polymer app for non root path为非根路径构建聚合物应用程序
【发布时间】:2018-08-19 22:44:54
【问题描述】:

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

我创建了一个非常简单的组件,当从根路径提供服务时,它可以与“polymer serve”和“polymer build”一起使用。

根据文档,您可以使用 --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,并且代码现在主要使用路径 /es5-bundled/,但仍需要在 /images/spinner 处引用引用的 spinner.gif .gif,为什么?

我的聚合物.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
}

【问题讨论】:

    标签: polymer polymer-3.x


    【解决方案1】:

    示例组件使用的是相对路径:

    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>`;
    

    【讨论】:

    • 我在从非根位置提供的应用程序中加载样式表资源时遇到了同样的问题。以下作品:&lt;link rel="stylesheet" href$="[[this.base_uri]]node_modules/ag-grid-community/dist/styles/ag-grid.css" &gt;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-21
    • 1970-01-01
    • 2016-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多