Open josh-collinsworth opened 2 months ago
1st Approach (Add a Dummy Element with id="top")
Open the affected Svelte component file, Add a div with id="top" at the top of the file.
<!-- src/routes/foo/bar.svelte -->
<div id="top"></div>
--> Rest of your page content
1.
<a href="#top">Back to top</a>
2nd Approach (Adjust SvelteKit Prerender Configuration)
Open your svelte.config.js file, Modify the prerender configuration to ignore missing IDs.
import adapter from '@sveltejs/adapter-static';
export default {
kit: {
adapter: adapter(),
prerender: {
handleMissingId: 'ignore', // Other options: 'fail', 'warn'
},
},
};
@Nirmit4604 I'm aware of both of these workarounds; however, neither should be needed because the code is valid to begin with. It is being inappropriately treated as an error, when it should not be. Developers shouldn't need to embrace workarounds when there's nothing wrong with the code in the first place.
Besides, it's entirely conceivable a developer might want #top
to work, but not want other missing IDs to pass.
So can we create a custom preprocessor to handle #top specifically and then integrate it into your svelte.config.js file?
The handleTopFragment preprocessor specifically looks for href="#top" and replaces it with a JavaScript-based scroll handle. This ensures that #top is handled correctly, while the prerender configuration (handleMissingId: 'warn') continues to apply to other missing IDs.
Describe the bug
The ID
#top
is a perfectly validhref
attribute, which can be used to scroll a user to the top of an HTML document. Per the HTML spec:This is also confirmed by MDN.
However, at build time, an anchor tag with
href="#top"
will throw an error:This shouldn't be the case, as
#top
is, again, a valid HTMLhref
value.Further, users shouldn't be forced to adjust their compiler options simply to be able to use something that's in the spec.
Reproduction
Run a static build on a SvelteKit site with a
<a href="#top">Top</a>
link presentLogs
System Info
Severity
annoyance
Additional Information
No response