4

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?

robd
  • 9,646
  • 5
  • 40
  • 59
  • Inside Papa Parse, the `Papa` variable is created on the global context. I'm not familiar with webpack or RequireJS or anything like that, but my guess is that webpack is messing with the global namespace...? – Matt Feb 17 '15 at 16:16
  • @Matt I did some experimentation and updated the question with my findings. I'm not sure what the best way is for a library to support direct inclusion in a web page via a – robd Feb 17 '15 at 19:19
  • See also https://github.com/mholt/PapaParse/issues/167 – robd Feb 18 '15 at 14:54

1 Answers1

3

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

robd
  • 9,646
  • 5
  • 40
  • 59
  • 3
    to elaborate more since I got stuck here, the es6 syntax is `import Papa from 'papaparse';`. From there you can use it as the documentation describes. – phouse512 Mar 25 '17 at 17:34