How to serve a json file with parcel without bundling it?

Viewed 4630

I'm making a project with parcel and typescript. It works great, but for one library I'm using, I would need to host a bunch of .json-files at a fixed directory:

The files look as following:

index.html
index.ts
tiles/
 | file.json
 | file0.json
 | subdirectory with *.json

In package.json, I include them as parcel *.html tiles/* (for start) and parcel build index.html tiles/*, but this results in the json files to be build into some .js file. I however need them to be served as is.

Any hints on how to tell parcel not to bundle them?

3 Answers

There is a npm-package doing exactly this: https://www.npmjs.com/package/parcel-plugin-static-files-copy

npm install -D parcel-plugin-static-files-copy to install (for development only)

Then, in package.json, add:

"staticFiles": {
    "staticPath": [
      {
        "staticPath": "tiles", -- copy all files from this directory at the root from your project...
        "staticOutDir": "tiles/" -- ... to this directory in dist/, so it becomes dist/tiles/<files>
      }
    ]
  }

``` 

Note that you have to define a `staticPath` in the list `staticPath`, this is a bit confusing at first.

You can override the transformer plugin used for JSON files in the .parcelrc file. It defaults to using @parcel/transformer-json, but you can use @parcel/transformer-raw to treat JSON files as assets.

.parcelrc

{
  "extends": "@parcel/config-default",
  "transformers": {
    "*.json": ["@parcel/transformer-raw"]
  }
}

If you're using Parcel 2, you can do something like this:

import jsonUrl from 'url:./data.json'

// Fetch the file asynchronously from the URL
fetch(jsonUrl)
  .then(response => response.json())
  .then(json => ...)
  ... etc. ...
Related