将ES6模块导入全局范围 [英] Import ES6 module into global scope
问题描述
TLDR :如何通过全局作用域(或引用另一个类中的导入类)来创建一个模块(通过ES6语法导入)?
TLDR: How can I make a module (imported via ES6 syntax) globally scoped (or reference an imported class inside another class)?
我正在从一个未正确实施的包中导入一个模块(不出口等),但遇到一些问题。
I'm importing a module from a package which wasn't implemented properly (no export etc) but am running into some issues.
我正在使用 var
将模块设置为全局(不太好),例如
What I am doing is using var
to set the module to global (not great) e.g.
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):
new window.Example(...)
这不是很好,因为我使用webpack并且更喜欢使用正确的es6语法
This works but it isn't great as I'm using webpack and would prefer to use the proper es6 syntax
import Example from './example';
然后在 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.
我尝试过像 window.Example = Example
但不起作用。
I've tried things like window.Example = Example
but it doesn't work.
推荐答案
如果您使用 webpack
,可以轻松设置。所以这里是一个简单的例子,如何实现它。
If you are using webpack
it's easy to setup it. 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>
另外如果你打开你的 bundle.js
文件你会看到webpack是如何为你做的。
Also if you open your bundle.js
file you will see how webpack did it for you.
var home = // main point
/*****/ (function(modules) blablabla)
...
我希望它会帮助你。
谢谢
这篇关于将ES6模块导入全局范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!