问题描述
我正在使用Webpack转换我的ES6类.假设捆绑包中有一个Service
类,可以通过其他捆绑包脚本导入该类.
I'm using Webpack to transpile my ES6 classes. Let's say there's a Service
class inside the bundle that can be imported by other bundled scripts.
class Service {
constructor() {
//
}
someMethod(data) {
//
}
}
export default Service;
现在,我在HTML主体(下面的伪代码)中有一个很小的内联脚本,该脚本需要调用Service
类中的方法,并使用在服务器端使用插入的数据来调用该方法.模板引擎,例如Twig或Blade.当然创建一个新的Service
对象是行不通的...
Now I've got a tiny inline script in the HTML body (pseudo-code below) that needs to call a method in that Service
class with data that is inserted server-side using a template engine such as Twig or Blade. Of course creating a new Service
object won't work...
<body>
...
<script>
var data = {{ $json_server_data }};
var service = new Service;
Service.someMethod(data);
</script>
</body>
我真的希望服务器数据可以内联使用,因为它可以防止进行额外的异步调用.用Service
类污染窗口名称空间的感觉就像是抛弃了类加载器的好处...
I'd really like the server data to be available inline as it prevents an additional asynchronous call. And polluting the window namespace with the Service
class feels like throwing away the benefits of a class loader...
您将如何解决这个问题?当然也欢迎提出采用其他方法的建议.
How would you tackle this? Suggestions about taking a different approach are also welcome of course.
推荐答案
在捆绑的javascript范围之外,您将无法使用服务"类.因此,您可能想使其成为 global ,并且您可以将其附加到窗口对象中.
You Service class won't be available outside the scope of the bundled javascript. So you probably want to make it global, and you can do that by attaching it into the window object.
// Service.js
class Service {
constructor() {
//
}
someMethod(data) {
//
}
}
window.Service = Service;
export default Service;
// usage
let myService = new Service();
这篇关于如何以内联< script>访问绑定的ES6类.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!