Preact-cli: Make static assets (robots.txt, 404.html...) available at domain's root

Created on 26 Nov 2017  路  4Comments  路  Source: preactjs/preact-cli

This is not a issue, rather it is the guidelines to achieve what the title explicitly says.

The problem

As of today, all static resources sit in /src/assets and are transferred to /build/assets after build. This means, in a traditional hosting configuration, all assets are served at www.example.com/assets/my-asset.txt.
For critical reasons, preact-cli already serves 2 resources at the root in the name of: favicon.ico, manifest.json (plus obviously all necessary HTML/CSS/JS bundles).

However, other use-cases require us to make resources available right at the root of our site/app like:

  • 404.html
  • 202.html (Surge.sh recommends it instead of index.html in order to server SPA)
  • robots.txt
  • sitemap_location.xml
  • ...

The solution

First of all: npm install --save-dev copy-webpack-plugin
then in preact.config.js file:

import CopyWebpackPlugin from 'copy-webpack-plugin'

export default config => {
    // Take everything under src/assets and copy it into root build destination
    config.plugins.push( new CopyWebpackPlugin([{ context: `${__dirname}/src/assets`, from: `*.*` }]) );
}

we got it ! :heart_eyes:

Like expressed in the commented line, this config will eventually take all files (not folders) at the root of /src/assets and copy them into the build --dest folder.
This means, /src/assets/robots.txt will be copied to /build/robots.txt (instead of /build/assets/robots.txt) and thus will be available at www.example.com/robots.txt.

All credits to @lukeed for pointing this to me, just thought I'd share the final snippet I adopted.
@developit I was not able to PR the wiki... so feel free to close this issue in favor of copy/pasting it into the wiki :)

Most helpful comment

Hi! preact-cli also accepts src/static directory. Everything inside this directory is left at the root of the build folder.
All the steps to do a custom webpack plugin are no more required in v3

All 4 comments

Cool! Glad you figured it out 馃拑

Just updated the wiki recipes, now that it's open.

Hello, i just had a problem while working on this part, we should specify the copy-webpack-plugin package to prevent the breaking changes, so if anyone had some problem try this:

npm install --save [email protected]

Those above plugin API will not work on latest version.

Hi! preact-cli also accepts src/static directory. Everything inside this directory is left at the root of the build folder.
All the steps to do a custom webpack plugin are no more required in v3

Was this page helpful?
0 / 5 - 0 ratings

Related issues

AlStar01 picture AlStar01  路  3Comments

hardcoar picture hardcoar  路  3Comments

hesselbom picture hesselbom  路  3Comments

andybons picture andybons  路  3Comments

ajay28kumar picture ajay28kumar  路  3Comments