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

1

5

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;
  • The trailingSlash option is mentioned by the SvelteKit docs
  • Removed _ from the default appDir: '_app' because it was mentioned somewhere that it might cause problems because of jekyll. This step should be unnecessary if an empty .nojekyll file is added to the project (not sure if to the absolute root of the project or in the folder that's hosted) Either way I saw no difference

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?

Blesbok answered 23/6, 2022 at 12:30 Comment(0)
B
7

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..?)

Blesbok answered 23/6, 2022 at 15:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.