本文介绍了将 ES6 模块导入全局范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

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');

因为我需要在我的类中像这样使用它(模块控制 this 并且类实例在全局范围内不可用,所以我不能像往常一样使用我的类会):

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

module.exports = {
  entry: 'test.js',
  output: {
    filename: 'bundle.js',
    path: 'home',
    library: 'home' // it assigns this module to the global (window) object
  }
  ...
}

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)
...

另外我建议看看 webpack library 配置.

Also i suggest look at webpack library configuration.

希望能帮到你.

谢谢

这篇关于将 ES6 模块导入全局范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 12:04