首先,我不建议您将 html 部分分离到另一个文件中。如果您觉得您的组件太大,只需将其分离到另一个组件中即可。
因为它是一个 javascript 文件(ES6 模块),所以它不能直接导入 html,但你可以将 template 函数分离到另一个文件并导入它。
index.html
<my-app></my-app>
<script type='module' src='app.js'></script>
app.js
import { PolymerElement } from '@polymer/polymer/polymer-element.js'
import home from './home.js'
class App extends PolymerElement {
static get properties () {
return {
count: Number
}
}
static get template () {
return home()
}
constructor () {
super()
this.count = 0
}
increaseCount () {
this.count += 1
}
}
customElements.define('my-app', App)
home.js
import { html } from '@polymer/polymer/polymer-element.js'
export default function () {
return html`
<h1>Home</h1>
<h2>Count: {{count}}</h2>
<button on-click='increaseCount'>Increase</button>
`
}
如果你想要一个真正的 html 文件。您可以使用fetch 下载html 文件并将其解析为template 函数。
app.js
import { PolymerElement, html } from '@polymer/polymer/polymer-element.js'
class App extends PolymerElement {
static get properties () {
return {
count: Number
}
}
constructor () {
super()
this.count = 0
}
increaseCount () {
this.count += 1
}
}
fetch('home.html')
.then(response => response.text())
.then(text => {
Object.defineProperty(App, 'template', {
get: function () {
return eval(`html\`${text}\``)
}
})
customElements.define('my-app', App)
})
home.html
<h1>Home</h1>
<h2>Count: {{count}}</h2>
<button on-click='increaseCount'>Increase</button>
或者您可以使用像 Webpack 这样的捆绑库,它允许您将 html 文件(通过加载器)导入到您的 javascript 文件中。
见polymer-skeleton 和这个article。