skip to Main Content

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.

2

Answers


  1. 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

    Login or Signup to reply.
  2. Parcel or other bundlers are complete overkill for this. All you need is a small script that takes the following steps:

    • Read the CSV using some csv parser into the structure you need.
    • Write a file in the current directory index.js using something like:
    fs.writeFileSync('./index.js', `export const data = ${JSON.stringify(myData)};`):
    

    And then the important part is that you do this during build time before you you publish the package. The published package only needs the generated file, not the csv or build scripts or any dependencies.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search