[英]Webpack: How to expose a class constructor to browser’s global namespace
I'm new to webpack and can't figure out how to expose a class constructor to the browser's global namespace. 我是webpack的新手,无法弄清楚如何向浏览器的全局命名空间公开类构造函数。 For example, how do I configure webpack so that the code below prints “hello world” in the console?
例如,如何配置webpack,以便下面的代码在控制台中显示“ hello world”? I've tried using
exports-loader
, expose-loader
, and script-loader
without success. 我尝试使用
exports-loader
, expose-loader
和script-loader
没有成功。
main.js main.js
class MyClass {
print() {
console.log('hello world');
}
}
index.html 的index.html
<!DOCTYPE html>
<html>
<head></head>
<body>
<script src="./dist/bundle.js"></script>
<script>
myClass = new MyClass;
myClass.print();
</script>
</body>
</html>
You can either: 您可以:
a) Expose your function (class) explicitly: a)显式公开您的函数(类):
main.js main.js
class MyClass {
print() {
console.log('hello world');
}
}
window.MyClass = MyClass;
Then you can call your constructor from global object by referencing MyClass
directly. 然后,您可以通过直接引用
MyClass
从全局对象中调用构造函数。
b) Configure webpack to expose your exports in a global object as follows: b)配置webpack,以在全局对象中公开您的导出,如下所示:
webpack.config.js webpack.config.js
module.exports = {
output: {
library: 'someName',
libraryTarget: 'umd',
globalObject: 'this'
}
}
Then you can call your constructor by referencing exported function (class) in a global variable configured as library
option in above config file. 然后,您可以通过在上述配置文件中配置为
library
选项的全局变量中引用导出的函数(类)来调用构造函数。 In this example someName.MyClass
. 在此示例中,
someName.MyClass
。 For this to work you must export the function in main.js file, as shown below. 为此,您必须将函数导出到main.js文件中,如下所示。
main.js main.js
export class MyClass {
print() {
console.log('hello world');
}
}
Refer to webpack output configuration for more specifics. 有关更多详细信息 ,请参阅webpack输出配置 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.