Import ES6 module to global scope

TL; DR . How can I make a module (imported through ES6 syntax) globally (or refer to an imported class inside another class)?


I am importing a module from a package that was not implemented correctly (without export, etc.), but I am encountering some problems.

I use varto install the module in global (not big), for example.

var Example = require('./node_modules/example/long_path_to_file.js');

How do I need to use it in my class (the module takes control this, and class instances are not available in the global scope, so I can not use my class as usual):

new window.Example(...)

This works, but it’s not great since I use webpack and prefer to use the correct es6 syntax

import Example from './example';

and then in example.js

export default Example = require('./node_modules/example/long_path_to_file.js');

, , .

, window.Example = Example, .

+8
2

webpack, . , , .

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

var home =  // main point
/*****/ (function(modules) blablabla)
...

webpack library .

, .

+10

, :

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 }
+5

All Articles