Home > Blockchain >  Serve a Parcel app subfolder as static files in express
Serve a Parcel app subfolder as static files in express

Time:11-19

I have a simple app (no frameworks) bundled with Parcel that I want to serve with express. I have divided the app in three different subfolders "assets", "pages" and "admin" so I have a similar structure to this:

src
  |
  --assets
  --admin
        |
        -- admin-folder
                      |
                      --index.html 
  --pages
        |
        --pages-folder
                     |
                     --index.html

Once the app is built and bundled with Parcel I want to serve both folders with two different express.static middlewares like:

app.use(express.static(path.join(__dirname, "dist", "pages"));
app.use("/admin", express.static(path.join(__dirname, "dist", "admin"));

I am not serving the whole "dist" folder because I wanted a cleaner URL without a "/pages" in the middle (eg. mywebsite.com/pages-folder and not mywebsite.com/pages/pages-folder) and because I can then authorize the access to the "/admin" part of the website. But, by doing so the bundle is broken since every reference (for example to the assets) is incorrect. How can I fix this issue?

CodePudding user response:

Although you could write a custom namer plugin to control the structure of the dist folder (see, for example, my answer to this question), I think that the approach you are taking of simply running parcel multiple times with different entries is probably simpler.

You can improve things further by specifiying the multiple entries in your package.json as different targets. That way you can build everything at once with a single call to the parcel build CLI command.

For example, if you had two source .html pages at src/pages/index.html and src/admin/index.hml, your package.json file might look like this:

{
  ...
  "targets": {
    "pages": {
      "source": "src/pages/index.html",
      "distDir": "dist/pages"
    },
    "admin": {
      "source": "src/admin/index.html",
      "distDir": "dist/admin"
    }
  },
  "scripts": {
    "build": "parcel build",
  },
  "devDependencies": {
    "parcel": "^2.0.1",
  }
}

Which would generate output at /dist/pages/index.html and /dist/admin/index.html.

  • Related