Search code examples
javascriptnode.jsblobparceljs

Create NPM package that packages a data blob


Objective

To create an npm package, that

  • exports a single constant, data that is an array of JS objects e.g.
const export data = [{a:1, b:2}, {a:3, b:4}];
  • works in the browser and Node (but if only one is possible, prefer browser);
  • is minimal size.

What I tried

I have a working Node implementation, which builds with Parcel. It packages a data file (.csv) and an index.js which reads (using d3) and parses (using fs) the csv at runtime to a constant variable data. This works fine in Node.

The problem

The bundled version fails, because of the reliance on fs, which is Node-only. So I would like to know:

  1. whether there is a suitable alternative to fs which is browser-friendly (I couldn't figure this out);
  2. whether there is a better, surely more straightforward way of packaging a blob of consistent data like this. It feels awfully like I am reinventing many wheels, with unnecessary pain.

Solution

  • Instead of putting the CSV in a .csv file, you can export a string from another JS file, e.g. data.js:

    export default `[paste csv here]`
    

    Then simply import it and use that file:

    import csv from "./data"
    

    This is nice because after bundling the CSV is in the same file, but it doesn't clutter your code.

    Alternatively, I found an npm package that's a parcel plugin that just might do it for you: https://www.npmjs.com/package/parcel-transformer-csv