Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use relative asset paths #4250

Merged
merged 25 commits into from Aug 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/wicked-spoons-leave.md
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': patch
---

Use relative asset paths where possible
3 changes: 2 additions & 1 deletion CONTRIBUTING.md
Expand Up @@ -48,6 +48,7 @@ You may need to install some dependencies first, e.g. with `npx playwright insta
If there are tests that fail on the CI, you can retrieve the failed screenshots by going to the summary page of the CI run. You can usually find this by clicking on "Details" of the check results, click "Summary" at the top-left corner, and then scroll to the bottom "Artifacts" section to download the archive.

It is very easy to introduce flakiness in a browser test. If you try to fix the flakiness in a test, you can run it until failure to gain some confidence you've fixed the test with a command like:

```
npx playwright test --workers=1 --repeat-each 1000 --max-failures 1 -g "accepts a Request object"
```
Expand All @@ -60,7 +61,7 @@ If you would like to test local changes to Vite or another dependency, you can b
{
// ...
"dependencies": {
"vite": "^2.0.0"
"vite": "^3.0.0"
},
"pnpm": {
"overrides": {
Expand Down
@@ -0,0 +1 @@
<h1>the fallback page was rendered</h1>
5 changes: 4 additions & 1 deletion packages/adapter-static/test/test.js
Expand Up @@ -14,8 +14,11 @@ run('prerendered', (test) => {
});

run('spa', (test) => {
test('generates a fallback page', ({ cwd }) => {
test('generates a fallback page', async ({ base, cwd, page }) => {
assert.ok(fs.existsSync(`${cwd}/build/200.html`));

await page.goto(`${base}/fallback/a/b/c`);
assert.equal(await page.textContent('h1'), 'the fallback page was rendered');
});

test('does not prerender pages without prerender=true', ({ cwd }) => {
Expand Down
2 changes: 1 addition & 1 deletion packages/create-svelte/templates/default/package.json
Expand Up @@ -13,7 +13,7 @@
"svelte": "^3.48.0",
"svelte-preprocess": "^4.10.6",
"typescript": "^4.7.4",
"vite": "^3.0.0"
"vite": "^3.0.4"
},
"type": "module",
"dependencies": {
Expand Down
Expand Up @@ -11,7 +11,7 @@
"@sveltejs/adapter-auto": "next",
"@sveltejs/kit": "next",
"svelte": "^3.46.0",
"vite": "^3.0.0"
"vite": "^3.0.4"
},
"type": "module",
"dependencies": {
Expand Down
Expand Up @@ -11,7 +11,7 @@
"@sveltejs/adapter-auto": "workspace:*",
"@sveltejs/kit": "workspace:*",
"svelte": "^3.44.0",
"vite": "^3.0.0"
"vite": "^3.0.4"
},
"type": "module"
}
32 changes: 25 additions & 7 deletions packages/kit/src/runtime/server/page/render.js
Expand Up @@ -150,9 +150,31 @@ export async function render_response({

const target = hash(body);

/**
* The prefix to use for static assets. Replaces `%sveltekit.assets%` in the template
* @type {string}
*/
let assets;

if (options.paths.assets) {
// if an asset path is specified, use it
assets = options.paths.assets;
} else if (state.prerendering?.fallback) {
// if we're creating a fallback page, asset paths need to be root-relative
assets = options.paths.base;
} else {
// otherwise we want asset paths to be relative to the page, so that they
// will work in odd contexts like IPFS, the internet archive, and so on
const segments = event.url.pathname.slice(options.paths.base.length).split('/').slice(2);
assets = segments.length > 0 ? segments.map(() => '..').join('/') : '.';
}

/** @param {string} path */
const prefixed = (path) => (path.startsWith('/') ? path : `${assets}/${path}`);

// prettier-ignore
const init_app = `
import { set_public_env, start } from ${s(options.prefix + entry.file)};
import { set_public_env, start } from ${s(prefixed(entry.file))};

set_public_env(${s(options.public_env)});

Expand Down Expand Up @@ -195,7 +217,7 @@ export async function render_response({
}

for (const dep of stylesheets) {
const path = options.prefix + dep;
const path = prefixed(dep);
const attributes = [];

if (csp.style_needs_nonce) {
Expand All @@ -217,7 +239,7 @@ export async function render_response({

if (page_config.router || page_config.hydrate) {
for (const dep of modulepreloads) {
const path = options.prefix + dep;
const path = prefixed(dep);
link_header_preloads.add(`<${encodeURI(path)}>; rel="modulepreload"; nopush`);
if (state.prerendering) {
head += `\n\t<link rel="modulepreload" href="${path}">`;
Expand Down Expand Up @@ -292,10 +314,6 @@ export async function render_response({
}
}

const segments = event.url.pathname.slice(options.paths.base.length).split('/').slice(2);
const assets =
options.paths.assets || (segments.length > 0 ? segments.map(() => '..').join('/') : '.');

// TODO flush chunks as early as we can
const html =
(await resolve_opts.transformPageChunk({
Expand Down
1 change: 0 additions & 1 deletion packages/kit/src/vite/build/build_server.js
Expand Up @@ -69,7 +69,6 @@ export class Server {
manifest,
method_override: ${s(config.kit.methodOverride)},
paths: { base, assets },
prefix: assets + '/',
prerender: {
default: ${config.kit.prerender.default},
enabled: ${config.kit.prerender.enabled}
Expand Down
26 changes: 15 additions & 11 deletions packages/kit/src/vite/build/utils.js
Expand Up @@ -88,9 +88,11 @@ export function find_deps(manifest, entry, add_dynamic_css) {
* @return {import('vite').UserConfig}
*/
export const get_default_config = function ({ config, input, ssr, outDir }) {
const prefix = `${config.kit.appDir}/immutable`;

return {
appType: 'custom',
base: assets_base(config.kit),
base: ssr ? assets_base(config.kit) : './',
build: {
cssCodeSplit: true,
// don't use the default name to avoid collisions with 'static/manifest.json'
Expand All @@ -101,11 +103,9 @@ export const get_default_config = function ({ config, input, ssr, outDir }) {
input,
output: {
format: 'esm',
entryFileNames: ssr ? '[name].js' : `${config.kit.appDir}/immutable/[name]-[hash].js`,
chunkFileNames: ssr
? 'chunks/[name].js'
: `${config.kit.appDir}/immutable/chunks/[name]-[hash].js`,
assetFileNames: `${config.kit.appDir}/immutable/assets/[name]-[hash][extname]`
entryFileNames: ssr ? '[name].js' : `${prefix}/[name]-[hash].js`,
chunkFileNames: ssr ? 'chunks/[name].js' : `${prefix}/chunks/[name]-[hash].js`,
assetFileNames: `${prefix}/assets/[name]-[hash][extname]`
},
preserveEntrySignatures: 'strict'
},
Expand All @@ -125,6 +125,14 @@ export const get_default_config = function ({ config, input, ssr, outDir }) {
},
ssr: {
noExternal: ['@sveltejs/kit']
},
worker: {
rollupOptions: {
output: {
entryFileNames: `${prefix}/workers/[name]-[hash].js`,
chunkFileNames: `${prefix}/workers/chunks/[name]-[hash].js`
}
}
}
};
};
Expand All @@ -134,11 +142,7 @@ export const get_default_config = function ({ config, input, ssr, outDir }) {
* @returns {string}
*/
export function assets_base(config) {
// TODO this is so that Vite's preloading works. Unfortunately, it fails
// during `svelte-kit preview`, because we use a local asset path. This
// may be fixed in Vite 3: https://github.com/vitejs/vite/issues/2009
const { base, assets } = config.paths;
return `${assets || base}/`;
return config.paths.assets || config.paths.base || './';
}

const method_names = new Set(['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH']);
Expand Down
1 change: 0 additions & 1 deletion packages/kit/src/vite/dev/index.js
Expand Up @@ -432,7 +432,6 @@ export async function dev(vite, vite_config, svelte_config, illegal_imports) {
base: svelte_config.kit.paths.base,
assets
},
prefix: '',
prerender: {
default: svelte_config.kit.prerender.default,
enabled: svelte_config.kit.prerender.enabled
Expand Down
4 changes: 2 additions & 2 deletions packages/kit/src/vite/index.js
Expand Up @@ -207,7 +207,7 @@ function kit() {
paths = {
build_dir: `${svelte_config.kit.outDir}/build`,
output_dir: `${svelte_config.kit.outDir}/output`,
client_out_dir: `${svelte_config.kit.outDir}/output/client/`
client_out_dir: `${svelte_config.kit.outDir}/output/client`
};

illegal_imports = new Set([
Expand All @@ -230,7 +230,7 @@ function kit() {
/** @type {import('vite').UserConfig} */
const result = {
appType: 'custom',
base: '/',
base: './',
build: {
rollupOptions: {
// Vite dependency crawler needs an explicit JS entry point
Expand Down
1 change: 0 additions & 1 deletion packages/kit/types/internal.d.ts
Expand Up @@ -239,7 +239,6 @@ export interface SSROptions {
base: string;
assets: string;
};
prefix: string;
prerender: {
default: boolean;
enabled: boolean;
Expand Down
4 changes: 2 additions & 2 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion sites/kit.svelte.dev/package.json
Expand Up @@ -21,7 +21,7 @@
"shiki-twoslash": "^3.0.2",
"svelte": "^3.48.0",
"typescript": "^4.7.4",
"vite": "^3.0.0",
"vite": "^3.0.4",
"vite-imagetools": "^4.0.3"
},
"type": "module"
Expand Down