我认为这不是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-bundle,并且代码现在主要使用路径/ es5-bundled /,但是仍需要在/ images / spinner中引用spinner.gif .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
}
答案 0 :(得分: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>`;