[英]Import ES6 module into global scope
TLDR : How can I make a module (imported via ES6 syntax) globally scoped (or reference an imported class inside another class)? TLDR :如何创建一个模块(通过ES6语法导入)全局作用域(或引用另一个类中的导入类)?
I'm importing a module from a package which wasn't implemented properly (no export etc) but am running into some issues. 我正在从一个未正确实现的包中导入模块(没有导出等)但是遇到了一些问题。
What I am doing is using var
to set the module to global (not great) eg 我正在做的是使用var
将模块设置为全局(不是很好),例如
var Example = require('./node_modules/example/long_path_to_file.js');
As I need to use it like so in my class (the module takes control of this
and class instances aren't available in the global scope so I can't use my class as I normally would): 因为我需要在我的类中使用它(模块控制了this
并且类实例在全局范围内不可用所以我不能像通常那样使用我的类):
new window.Example(...)
This works but it isn't great as I'm using webpack and would prefer to use the proper es6 syntax 这可行,但它不是很好,因为我使用webpack并且更喜欢使用正确的es6语法
import Example from './example';
and then in example.js
然后在example.js
export default Example = require('./node_modules/example/long_path_to_file.js');
However this means it is no longer global scoped, and I'm unable to find a fix. 但是这意味着它不再是全局范围的,我无法找到修复方法。
I've tried things like window.Example = Example
but it doesn't work. 我尝试过像window.Example = Example
但它不起作用。
If you are using webpack
it's easy to setup it. 如果您使用webpack
则可以轻松设置它。 So here is a simple example how to implement it. 所以这是一个如何实现它的简单示例。
webpack.config.js webpack.config.js
module.exports = {
entry: 'test.js',
output: {
filename: 'bundle.js',
path: 'home',
library: 'home' // it assigns this module to the global (window) object
}
...
}
some.html some.html
<script>console.log(home)</script>
Also if you open your bundle.js
file you will see how webpack did it for you. 此外,如果您打开bundle.js
文件,您将看到webpack是如何为您完成的。
var home = // main point
/*****/ (function(modules) blablabla)
...
Also i suggest look at webpack library configuration. 另外我建议看一下webpack库配置。
I hope it will help you. 我希望它会对你有所帮助。
Thanks 谢谢
I've done some testing and this works correctly: 我做了一些测试,这是正常的:
import './middleman';
// './middleman.js'
window.Example = require('./example.js').default
// OR
window.Example = require('./example.js').Example
// './example.js'
export function Example() {
this.name = 'Example'
}
export { Example as default }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.