9

Using Preact CLI is it possible to set the path where the app will be hosted outside of the root directory?

For instance hosting the app at http://mywebsite.com/relativepath/index.html

Tim Arney
  • 1,776
  • 2
  • 18
  • 23

2 Answers2

12

You have several problems to solve:

1. Get Webpack to output the correct paths in your html

This is done via creating a preact.config.js in your root folder, and put the following in there

export default (config) => {
  config.output.publicPath = '/relativepath/';
};

2. Set your navigation and assets links in your app

The best way to solve it in my opinion is to use a global variable which you can be used in your app. So again, edit the preact.config.js to the following:

  export default (config, env, helpers) => {
     config.output.publicPath = '/relativepath/';

    // use the public path in your app as 'process.env.PUBLIC_PATH'
    config.plugins.push(
      new helpers.webpack.DefinePlugin({
        'process.env.PUBLIC_PATH': JSON.stringify(config.output.publicPath || '/')
      })
    );
  };

3. Routing

When using your preact app, it should be no problem to navigate. However, if you try to load a fresh URL e.g. www.myserver.com/relativepath/mything/9, the server doesn't know that it should load your single page app living at www.myserver.com/relativepath/index.html

You have two options:

a) Server-side routing

Make sure your all the requests to relativepath (including e.g. relativepath/mything/9) will be rewritten to your app's relativepath/index.html (in case of using Apache). Then your Javascript can process the routes, e.g. preact-router

b) Client-side routing (recommended)

The easier option for enabling reloading of URLs is to use hash urls, thereby avoid going through the server when loading a URL.

Your URLs will look something like www.myserver.com/relativepath/#/mything/9 The server ignores the part after # and only loads (hopefully) /relativepath/index.html

You can use e.g. the preact-router with Hash History to avoid server-side routing, read about it here https://github.com/developit/preact-router#custom-history

MonkeyVoodoo
  • 538
  • 5
  • 17
0

I'm proxying from http-proxy-middleware to the preact-cli dev server and these settings worked for me in preact.config.js

export default (config, env, helpers) => {
    config.output.publicPath = '/relativepath';
    config.devServer.devMiddleware.publicPath = "/relativepath";
};
SirGanya
  • 142
  • 1
  • 9