Import ES6 module into global scope

前端 未结 2 1558
慢半拍i
慢半拍i 2020-12-06 10:47

TLDR: How can I make a module (imported via ES6 syntax) globally scoped (or reference an imported class inside another class)?


I\'m importing

相关标签:
2条回答
  • 2020-12-06 11:28

    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

    0 讨论(0)
  • 2020-12-06 11:29

    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 }
    
    0 讨论(0)
提交回复
热议问题