Monday, June 3, 2024
20
rated 0 times [  26] [ 6]  / answers: 1 / hits: 25633  / 8 Years ago, wed, february 24, 2016, 12:00:00

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.



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


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


and then in 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.


More From » ecmascript-6

 Answers
9

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>


Also if you open your bundle.js file you will see how webpack did it for you.



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


Also i suggest look at webpack library configuration.



I hope it will help you.



Thanks


[#63186] Monday, February 22, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bruno

Total Points: 602
Total Questions: 100
Total Answers: 111

Location: Tajikistan
Member since Sun, Aug 29, 2021
3 Years ago
bruno questions
Sat, Jul 11, 20, 00:00, 4 Years ago
Sun, Jun 28, 20, 00:00, 4 Years ago
Thu, Mar 12, 20, 00:00, 4 Years ago
Thu, Feb 6, 20, 00:00, 4 Years ago
Sat, Aug 10, 19, 00:00, 5 Years ago
;