Search code examples
javascriptwebpackpapaparse

Loading PapaParse dynamically with webpack


I am using PapaParse to load a csv file from a file input.

Currently, I have a working version where I load PapaParse using a script tag:

<script type="text/javascript" src="papaparse.js" ></script>

And handle the change event:

Papa.parse(event.target.files[0], {
  complete: function(results) {
  ...
  }
}

I now want to use webpack to bundle up my js and I want to load PapaParse dynamically just when I need it, not every time into the global namespace. Something like this:

require("./papaparse.js").Papa.parse(event.target.files[0], {
  complete: function(results) {
  ...
  }
}

Unfortunately this gives me the error Uncaught ReferenceError: Papa is not defined from this line in the PapaParse library:

if (!config.chunkSize)
            config.chunkSize = Papa.LocalChunkSize;

Is there any way of making this work?

[Edit]

I'm completely new to requirejs / webpack, so I'm not sure if this is the right way to fix this, but I managed to get this working (unfortunately still polluting the window namespace) by using the following shim configuration:

require("imports?this=>window!exports?global.Papa!./papaparse.js").parse(event.target.files[0], {
  complete: function(results) {
  ...
  }
}

As I understand it, the first directive (imports?this=>window) uses the imports loader to set the global parameter to be the window object (as opposed to an empty object). This makes the calls in PapaParse to global.document and global.postMessage() work (and also seems to make the unqualified calls to Papa work - ie the ones not prefixed as global.Papa). The second directive (exports?global.Papa) means that the Papa object is exported as the returned object from the require call.

I would be interested if someone experienced with webpack could advise whether this is the correct way to deal with this?


Solution

  • PapaParse should now work with webpack as of this commit. See also PR172.