内含模板文字的导入模块只能访问全局变量。如何从一个类访问变量?
template.js(定位类)
export var literal = {
base: `<h1>${ foo.copy.ternary }</h1>
<div>${ foo.copy.title }</div>
`
}
index.html(在下面的示例中,我得到一个ReferenceError:找不到变量)
<!DOCTYPE html>
<html>
<body>
<div id=host></div>
</body>
<script type="text/javascript">
class Foo {
constructor() {
this.copy = {
title: 'Discovering Template Literals',
subtitle: 'Effortless client-side rendering awaits.',
body: 'You will never want to go back to normal strings again.',
ternary: 'Ternary Condition'
};
};
};
</script>
<script type="module">
let foo = new Foo();
import * as templates from './templates.js'
document.getElementById( "host" ).innerHTML = templates.literal.base;
</script>
</html>
template.js
export var literal = {
base: `<h1>${ copy.ternary }</h1>
<div>${ copy.title }</div>
`
}
index.html(使用全局变量)
<!DOCTYPE html>
<html>
<body>
<div id=host></div>
</body>
<script type="text/javascript">
var copy = {
title: 'Discovering Template Literals',
subtitle: 'Effortless client-side rendering awaits.',
body: 'You will never want to go back to normal strings again.',
ternary: 'Ternary Condition'
};
</script>
<script type="module">
import * as templates from './templates.js'
document.getElementById( "host" ).innerHTML = templates.literal.base;
</script>
</html>
最佳答案
你的
export var literal = {
base: `<h1>${ foo.copy.ternary }</h1>
<div>${ foo.copy.title }</div>
`
}
将对
foo.copy.ternary
等的求值结果插值到构造的字符串中,该字符串被分配给base
属性。但是foo
不在模块范围内,因此在运行模块时将引发错误。而不是导出模板文字(这与导出静态字符串相同,除了错误),而是导出一个以
foo
作为参数,对函数中的模板文字求值并返回构造的字符串的函数:export var literal = {
base(foo) {
return `<h1>${ foo.copy.ternary }</h1>
<div>${ foo.copy.title }</div>
`;
}
}
然后调用:
document.getElementById( "host" ).innerHTML = templates.literal.base(foo);