Corrl
Corrl

Reputation: 7699

How to host a SvelteKit (adapter-static) project on GitHub pages?

I would like to host a SvelteKit project on GitHub pages but apparently I haven't found the right settings yet. I tried

import adapter from '@sveltejs/adapter-static';

/** @type {import('@sveltejs/kit').Config} */
const config = {
    kit: {
        adapter: adapter({
            pages: 'build',
            assets: 'build',
            fallback: null,
            precompress: false
        }),
        appDir: 'app',
        prerender: {
            default: true,
        },
        trailingSlash: 'always',
    }
};

export default config;

When running preview after building everything looks fine. But when opening the deployed page all the .css and .js files have a 404 status. Which setting am I missing?

Upvotes: 6

Views: 2410

Answers (1)

Corrl
Corrl

Reputation: 7699

Since the project hosted on GitHub pages will be served from a url like this https://{org}.github.io/{repo} a base path must be added and a config like this

const config = {
    kit: {
        adapter: adapter({
            pages: 'build',
            assets: 'build',
            fallback: null,
            precompress: false
        }),
        prerender: {
            default: true,
        },
        trailingSlash: 'always',
        paths: {
            base: '/repo_name'
        }
    }
};

plus the empty .nojekyll file sitting in the hosted directory should work.

Unfortunately there currently seem to be some problems when having a base path

first when running dev mode, so only set the base path when building like this

const dev = process.env.NODE_ENV === 'development';

const config = {
    kit: {
        ...
        paths: {
            base: dev ? '' : '/repo_name',
        }
    }
};

And for the errors when buidling there's this workaround for the links

<script>
import { base } from '$app/paths';
</script>

<a href="{base}/route">Route</a>

With these adjustments dev and build mode should run and hosting on GitHub pages be possible. preview mode still seems to be broken (or is this expected/normal that serving the build locally just can't work because of the base path..?)

Upvotes: 8

Related Questions