我正在为自定义元素编写一个装饰器,主要代码是:
interface CustomElementOptions {
selector: string,
template?: { default: string };
}
function CustomElement(options: CustomElementOptions) {
return (target: CustomElementConstructor) => {
if(options.template) {
const template = document.createElement('template');
template.innerHTML = options.template.default;
Object.defineProperty(target.prototype, 'template', {
value: template,
});
}
window.customElements.define(options.selector, target as any);
};
}
@CustomElement({
selector: 'test-span',
template: require('./template.html'), // <---------------------- I want to change here with `templateUrl`
})
export class SpanElement extends HTMLElement {
public template?: HTMLTemplateElement;
constructor() {
super();
if(this.template) {
this.appendChild(this.template.content.cloneNode(true));
}
}
}
我现在raw-loader
用来加载 html 模板,但这还不够优雅,我想像 Angular:
@CustomElement({
selector: 'test-span',
templateUrl: './template.html', // <---------------------- templateUrl
})
export class SpanElement extends HTMLElement { ... }
但我不能在装饰器中使用 require 或 import ,错误消息如下:
Uncaught Error: Cannot find module './template.html'
at webpackEmptyContext (app|sync:2)
at application.ts:10
at __webpack_modules__../src/app/application.ts.__decorate (index.js:6)
at Object../src/app/application.ts (application.ts:20)
at __webpack_require__ (bootstrap:18)
at Object../src/main.ts (main.ts:1)
at __webpack_require__ (bootstrap:18)
at startup:3
at startup:5
angular-cli 里面有什么魔力?我尽力了,谢谢你的帮助!