Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to handle output files in parcel

Tags:

parceljs

I have a project with this structure:

src
 |- index.pug
 | - layout
 |     |- index.less
 | - scripts
 |     |- index.js

For now, when I run parcel build src/index.pug, all the files are bundled and I've got this on the distribution folder:

dist
  |- index.html
  |- index.12345.css
  |- index.12345.js

When I was expected something like:

ist
  |- index.html
  |- layout
  |    |- index.12345.css
  |- scripts
  |    |- index.12345.js

So, my question is: Can I specify the output path for my CSS, js, and images using ParcelJS?

like image 635
Ibrahim Kamal Avatar asked Nov 07 '22 06:11

Ibrahim Kamal


1 Answers

Unfortunately, this isn't supported out-of-the box by parcel. Parcel v1 you can use this plugin. For parcel v2, it is possible to write a namer plugin that accomplishes this.

Here's the code (in typescript):

    import { Namer } from "@parcel/plugin";
    import type { Bundle } from "@parcel/types";
    import path from "path";
    
    export default new Namer({
      name({ bundle }) {
        switch (bundle.type) {
          case "js":
            return getPathWithFolder("scripts", bundle);
          case "less":
            return getPathWithFolder("layout", bundle);
          case "css":
            return getPathWithFolder("layout", bundle);
          default:
            return null;
        }
      },
    });
    
    function getPathWithFolder(folderName: string, bundle: Bundle): string | null {
      const filePath = bundle.getMainEntry()?.filePath;
      if (!filePath) return null;
      let nameWithoutExtension = path.basename(filePath, path.extname(filePath));
      if (!bundle.needsStableName) {
        // See: https://parceljs.org/plugin-system/namer/#content-hashing
        nameWithoutExtension += "." + bundle.hashReference;
      }
      return `${folderName}/${nameWithoutExtension}.${bundle.type}`;
    }

Then, supposing the above code was published in a package called parcel-namer-folders, you would add it to your parcel pipeline with this .parcelrc:

    {
      "extends": "@parcel/config-default",
      "namers": ["parcel-namer-folders", "..."]
    }

Here is an example repo where this is working.

like image 154
Andrew Stegmaier Avatar answered Jan 01 '23 22:01

Andrew Stegmaier