Browserify-shim does not export implicit global values ​​when they have a var variable

According to the browserify-shim docs, you can specify which globals browserify-shim should be exposed from your deprecated modules using the following syntax in package.json :

 { "browserify-shim": { "legacyModule": "myVar" } } 

I want the obsolete module to be accessible via require('legacyModule') and window.myVar .

From my experience, if the non-commonjs module I'm trying to use uses window.myVar = x or just myVar = x , the module is displayed globally and is accessible via require() , as expected.

However , when an obsolete module uses var myVar = x , this is why the problem is that the module is only accessible through require('legacyModule') and not through window.myVar .

The browser-firmware documentation states that:

In addition, it handles the following real-world cases:

  • Modules that simply declare var foo = ... at the script level and assume that it is attached to the window object. Because the only way they will ever be executed is through the global context - "um ... NO ?!"
+6
source share
1 answer

As @EvanDull suggested, I believe that browser scrolling cannot be designed this way, and the documentation lacks clarity. In the debugging that I did, it did not seem that Browsify-shim is intended to set a global variable when it "processes" var foo = ... Where the documentation says that it handles this, I believe that this means that it is not processing the global object yet, and it will still export the value of this variable for CommonJS, for example. var foo = ...; module.exports = foo; so it could be require() 'd. While you would like it to execute var foo = ...; window.foo = module.exports = foo; var foo = ...; window.foo = module.exports = foo; And of course, since he does not do this and is looking at wrappers, legacy code in the function, var foo only creates a local variable.

There are a number of possible workarounds that you can use now:

  • If you don't mind editing obsolete scripts, you can simply remove var , and that should take care of that.

  • You can pull obsolete scripts through separate <script> tags, rather than linking them.

  • You can use browser transform to add the additional purpose of global.myVar = myVar to the end of the old script. This will require adaptation of the conversion for each specific script that you need.

  • You can make the first file in your script package, which will do something like:

     [['legacyModule, 'myVar'], ...].forEach(function (mod) { window[mod[1]] = require(mod[0]); }); 
+5
source

Source: https://habr.com/ru/post/985280/


All Articles