Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Base URL for Preact CLI

Tags:

preact

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

like image 575
Tim Arney Avatar asked Aug 17 '17 18:08

Tim Arney


People also ask

What is preact CLI?

Preact CLI helps you get started building a blazing-fast Preact PWA in just a few seconds. Preact CLI takes the pain out of starting a new project, getting you up and running instantly with a minimal and understandable project structure.

Does Preact use JSX?

Rendering JSX Out of the box, Preact provides an h() function that turns your JSX into Virtual DOM elements (here's how). It also provides a render() function that creates a DOM tree from that Virtual DOM.


1 Answers

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

like image 137
MonkeyVoodoo Avatar answered Nov 07 '22 19:11

MonkeyVoodoo