How expose a exported function into global scope with babel and webpack

前端 未结 2 1394
悲&欢浪女
悲&欢浪女 2020-12-18 22:44

How can I compile my code with webpack and babel so that the exported function is available in the global scope.

So for example:

export function test         


        
相关标签:
2条回答
  • 2020-12-18 23:12

    check out: https://github.com/webpack/docs/wiki/library-and-externals#examples

    By setting the library output property to whatever name you want to wrap your globals would allow you to then call: YourLibrary.test();

    module.exports = {
        entry: ['./_js/script.js'],
        output: {
           library: 'YourLibrary',
            path: __dirname,
            filename: './build/script.js'
        }
    
    0 讨论(0)
  • 2020-12-18 23:26

    You can easily set a property on the global window object. This will expose your object to the global scope.

    function test() {
      console.log('test');
    }
    
    window.test = test;
    

    If you are developing a piece of code that does not represent a library but just some operations or functionalities to operate in global scope, I would prefer this method over to setting the library output property as mentioned in the accepted answer.

    0 讨论(0)
提交回复
热议问题