1

I'm currently working on a build process that uses webpack. One of the dependencies that I need to include in my bundle is an old third-party library that doesn't follow any module patterns. I wan't to just include it in it's raw form, but it's coded in such a way that the usual techniques don't work.

The offending library is coded a bit like this:

function OldLibrary() {
  console.log('What are modules?');
};
var foo = window.OldLibrary;
// Proceeds to use foo without a care in the world

As you can see from the code above, the library assumes that it will always be in the global context, and so it doesn't bother to explicitly set window.OldLibrary.

At first I tried using script-loader, but this wraps the script inside function(module, exports) {}, which means that OldLibrary now belongs to the scope of that function instead of window's and this causes an exception. I also tried using imports loader like imports?this=>window, but this only sets this to window, so it doesn't have effect on functions that are supposed to be global.

Finally, I tried out raw-loader, but this just adds the script as a string, so it's not executed. Is there a way to tell Webpack to just concatenate the script as is without wrapping it inside another function?

Edit

It turns out that script-loader does actually handle this library as expected, I just wasn't matching it properly because it was the only file that didn't have a .min.js extension. I'm still interested in finding a way to concatenate scripts without wrapping them in functions, if possible.

JayPea
  • 9,551
  • 7
  • 44
  • 65
  • _"Finally, I tried out `raw-loader`, but this just adds the script as a string, so it's not executed"_ Have not tried `webpack`, though you should be able to use `Function()` or `Blob()` to execute string as `javascript`. – guest271314 Nov 08 '16 at 22:55
  • @guest271314 interesting, do you know if there is a way to have webpack wrap the output from the `raw-loader` with a `Function()`? – JayPea Nov 08 '16 at 23:38
  • Could you just put `let window;` at the top and `export window` at the bottom? – Bill Nov 08 '16 at 23:55
  • So long as the library doesn't refer to global methods and properties of `window` should be all good – Bill Nov 08 '16 at 23:56
  • `var script = "function OldLibrary() { console.log('What are modules?'); };var foo = window.OldLibrary;"; var fn = new Function("return " + script);fn()()` Though would not set `foo` to `window.OldLibrary`. Using `Blob()`, if possible, should return expected result. – guest271314 Nov 09 '16 at 00:02
  • @JayPea See [Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) , [How to cache a downloaded javascript fle which is downloaded using script tag](http://stackoverflow.com/questions/39784514/how-to-cache-a-downloaded-javascript-fle-which-is-downloaded-using-script-tag/) – guest271314 Nov 09 '16 at 00:14

0 Answers0