Skip to content

Instantly share code, notes, and snippets.

@mathisonian
Last active Feb 11, 2020
Embed
What would you like to do?
Loading data with Parcel

This is a quick guide to loading static files with Parcel. There are two ways to load data in JavaScript:

  • including the data in the JavaScript bundle itself
  • fetching the data as an external resource

Including data directly in the JavaScript bundle

This is the preferred way of doing things if your data payload is relatively small (<1 MB) as it will lead to fewer network requests (which often gives better perfromance).

Loading a JSON file

Because JSON is a native representation for JavaScript, this is a one-liner

const myData = require('./my-data.json');
console.log(myData)

Fetching data as an external resource

Loading a CSV file

If you do the same thing with a CSV file, you'll end up with a string

const myDataLocation = require('./my-data.csv');
console.log(myDataLocation) // prints out a string, not parsed data

this string points to the resource location of the CSV file. To fetch the data, run

const myDataLocation = require('./my-data.csv');
console.log(myDataLocation) // prints out a string, not parsed data

d3.csv(myDataLocation).then((data) => {
  console.log(data)
})

Getting Advanced with static files

If you want more control over the static files (for example if you want to dynamically load a dataset based on user-provided queries), you may want to ditch the require() statement and organize things yourself.

In this case you'll need the Parcel static files plugin. To use it, first install the plugin (npm install --save-dev parcel-plugin-static-files-copy).

Then, create a folder called static in the root of your project directory. Then anything you place in this folder is available. For example if I place a file called data.json into the static folder, I could then run

d3.json('data.json').then(data => console.log(data))

and things would work as expected.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment