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:
- whether there is a suitable alternative to
fs
which is browser-friendly (I couldn’t figure this out); - 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
Instead of putting the CSV in a
.csv
file, you can export a string from another JS file, e.g.data.js
:Then simply import it and use that file:
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
Parcel or other bundlers are complete overkill for this. All you need is a small script that takes the following steps:
index.js
using something like: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.