Skip to content
This repository has been archived by the owner on Jan 11, 2023. It is now read-only.

Commit

Permalink
Add support for custom route file extensions.
Browse files Browse the repository at this point in the history
  • Loading branch information
pngwn committed May 17, 2019
1 parent ce50c2f commit e7b1aa3
Show file tree
Hide file tree
Showing 24 changed files with 346 additions and 16 deletions.
4 changes: 3 additions & 1 deletion src/api/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ type Opts = {
static?: string;
legacy?: boolean;
bundler?: 'rollup' | 'webpack';
ext?: string;
oncompile?: ({ type, result }: { type: string, result: CompileResult }) => void;
};

Expand All @@ -32,6 +33,7 @@ export async function build({

bundler,
legacy = false,
ext,
oncompile = noop
}: Opts = {}) {
bundler = validate_bundler(bundler);
Expand Down Expand Up @@ -68,7 +70,7 @@ export async function build({

fs.writeFileSync(`${dest}/template.html`, minify_html(template));

const manifest_data = create_manifest_data(routes);
const manifest_data = create_manifest_data(routes, ext);

// create src/node_modules/@sapper/app.mjs and server.mjs
create_app({
Expand Down
15 changes: 9 additions & 6 deletions src/api/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ type Opts = {
hot?: boolean,
'devtools-port'?: number,
bundler?: 'rollup' | 'webpack',
port?: number
port?: number,
ext: string
};

export function dev(opts: Opts) {
Expand All @@ -47,7 +48,7 @@ class Watcher extends EventEmitter {
}
port: number;
closed: boolean;

dev_port: number;
live: boolean;
hot: boolean;
Expand All @@ -67,6 +68,7 @@ class Watcher extends EventEmitter {
unique_warnings: Set<string>;
unique_errors: Set<string>;
}
ext: string;

constructor({
cwd = '.',
Expand All @@ -80,7 +82,8 @@ class Watcher extends EventEmitter {
hot,
'devtools-port': devtools_port,
bundler,
port = +process.env.PORT
port = +process.env.PORT,
ext
}: Opts) {
super();

Expand All @@ -95,7 +98,7 @@ class Watcher extends EventEmitter {
output: path.resolve(cwd, output),
static: path.resolve(cwd, static_files)
};

this.ext = ext;
this.port = port;
this.closed = false;

Expand Down Expand Up @@ -161,7 +164,7 @@ class Watcher extends EventEmitter {
let manifest_data: ManifestData;

try {
manifest_data = create_manifest_data(routes);
manifest_data = create_manifest_data(routes, this.ext);
create_app({
bundler: this.bundler,
manifest_data,
Expand Down Expand Up @@ -189,7 +192,7 @@ class Watcher extends EventEmitter {
},
() => {
try {
const new_manifest_data = create_manifest_data(routes);
const new_manifest_data = create_manifest_data(routes, this.ext);
create_app({
bundler: this.bundler,
manifest_data, // TODO is this right? not new_manifest_data?
Expand Down
22 changes: 15 additions & 7 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ prog.command('dev')
.option('--static', 'Static files directory', 'static')
.option('--output', 'Sapper output directory', 'src/node_modules/@sapper')
.option('--build-dir', 'Development build directory', '__sapper__/dev')
.option('--ext', 'Custom Route Extension', '.svelte .html')
.action(async (opts: {
port: number,
open: boolean,
Expand All @@ -43,7 +44,8 @@ prog.command('dev')
routes: string,
static: string,
output: string,
'build-dir': string
'build-dir': string,
ext: string
}) => {
const { dev } = await import('./api/dev');

Expand All @@ -59,7 +61,8 @@ prog.command('dev')
'dev-port': opts['dev-port'],
live: opts.live,
hot: opts.hot,
bundler: opts.bundler
bundler: opts.bundler,
ext: opts.ext
});

let first = true;
Expand Down Expand Up @@ -151,6 +154,7 @@ prog.command('build [dest]')
.option('--src', 'Source directory', 'src')
.option('--routes', 'Routes directory', 'src/routes')
.option('--output', 'Sapper output directory', 'src/node_modules/@sapper')
.option('--ext', 'Custom Route Extension', '.svelte .html')
.example(`build custom-dir -p 4567`)
.action(async (dest = '__sapper__/build', opts: {
port: string,
Expand All @@ -159,12 +163,13 @@ prog.command('build [dest]')
cwd: string,
src: string,
routes: string,
output: string
output: string,
ext: string
}) => {
console.log(`> Building...`);

try {
await _build(opts.bundler, opts.legacy, opts.cwd, opts.src, opts.routes, opts.output, dest);
await _build(opts.bundler, opts.legacy, opts.cwd, opts.src, opts.routes, opts.output, dest, opts.ext);

const launcher = path.resolve(dest, 'index.js');

Expand Down Expand Up @@ -199,6 +204,7 @@ prog.command('export [dest]')
.option('--static', 'Static files directory', 'static')
.option('--output', 'Sapper output directory', 'src/node_modules/@sapper')
.option('--build-dir', 'Intermediate build directory', '__sapper__/build')
.option('--ext', 'Custom Route Extension', '.svelte .html')
.action(async (dest = '__sapper__/export', opts: {
build: boolean,
legacy: boolean,
Expand All @@ -212,11 +218,12 @@ prog.command('export [dest]')
static: string,
output: string,
'build-dir': string,
ext: string
}) => {
try {
if (opts.build) {
console.log(`> Building...`);
await _build(opts.bundler, opts.legacy, opts.cwd, opts.src, opts.routes, opts.output, opts['build-dir']);
await _build(opts.bundler, opts.legacy, opts.cwd, opts.src, opts.routes, opts.output, opts['build-dir'], opts.ext);
console.error(`\n> Built in ${elapsed(start)}`);
}

Expand Down Expand Up @@ -265,7 +272,8 @@ async function _build(
src: string,
routes: string,
output: string,
dest: string
dest: string,
ext: string
) {
const { build } = await import('./api/build');

Expand All @@ -276,7 +284,7 @@ async function _build(
src,
routes,
dest,

ext,
oncompile: event => {
let banner = `built ${event.type}`;
let c = (txt: string) => colors.cyan(txt);
Expand Down
5 changes: 3 additions & 2 deletions src/core/create_manifest_data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ import svelte from 'svelte/compiler';
import { Page, PageComponent, ServerRoute, ManifestData } from '../interfaces';
import { posixify, reserved_words } from '../utils';

const component_extensions = ['.svelte', '.html']; // TODO make this configurable (to include e.g. .svelte.md?)
export default function create_manifest_data(cwd: string, extensions: string = '.svelte .html'): ManifestData {

const component_extensions = extensions.split(' ');

export default function create_manifest_data(cwd: string): ManifestData {
// TODO remove in a future version
if (!fs.existsSync(cwd)) {
throw new Error(`As of Sapper 0.21, the routes/ directory should become src/routes/`);
Expand Down
60 changes: 60 additions & 0 deletions test/apps/custom-extension/rollup.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import resolve from 'rollup-plugin-node-resolve';
import replace from 'rollup-plugin-replace';
import svelte from 'rollup-plugin-svelte';

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

const config = require('../../../config/rollup.js');

export default {
client: {
input: config.client.input(),
output: config.client.output(),
plugins: [
replace({
'process.browser': true,
'process.env.NODE_ENV': JSON.stringify(mode)
}),
svelte({
extensions: ['.whokilledthemuffinman', '.jesuslivesineveryone', '.mdx', '.svelte', '.html'],
dev,
hydratable: true,
emitCss: true
}),
resolve()
]
},

server: {
input: config.server.input(),
output: config.server.output(),
plugins: [
replace({
'process.browser': false,
'process.env.NODE_ENV': JSON.stringify(mode)
}),
svelte({
extensions: ['.whokilledthemuffinman', '.jesuslivesineveryone', '.mdx', '.svelte', '.html'],
generate: 'ssr',
dev
}),
resolve({
preferBuiltins: true
})
],
external: ['sirv', 'polka']
},

serviceworker: {
input: config.serviceworker.input(),
output: config.serviceworker.output(),
plugins: [
resolve(),
replace({
'process.browser': true,
'process.env.NODE_ENV': JSON.stringify(mode)
})
]
}
};
9 changes: 9 additions & 0 deletions test/apps/custom-extension/src/client.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import * as sapper from '@sapper/app';

window.start = () => sapper.start({
target: document.querySelector('#sapper')
});

window.prefetchRoutes = () => sapper.prefetchRoutes();
window.prefetch = href => sapper.prefetch(href);
window.goto = href => sapper.goto(href);
6 changes: 6 additions & 0 deletions test/apps/custom-extension/src/routes/[slug].mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<script>
import { stores } from '@sapper/app';
const { page } = stores();
</script>

<h1>{$page.params.slug.toUpperCase()}</h1>
3 changes: 3 additions & 0 deletions test/apps/custom-extension/src/routes/_error.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<h1>hi</h1>

<p>hi</p>
1 change: 1 addition & 0 deletions test/apps/custom-extension/src/routes/a.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<h1>a</h1>
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<h1>Tremendous!</h1>
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<h1>Great success!</h1>

<a href="a">a</a>
<a href="ambiguous/ok.json">ok</a>
<a href="echo-query?message">ok</a>
<a href="echo-query?p=one&p=two">ok</a>

<div class='hydrate-test'></div>
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<h1>Bazooom!</h1>
9 changes: 9 additions & 0 deletions test/apps/custom-extension/src/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import polka from 'polka';
import * as sapper from '@sapper/server';

import { start } from '../../common.js';

const app = polka()
.use(sapper.middleware())

start(app);
81 changes: 81 additions & 0 deletions test/apps/custom-extension/src/service-worker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import * as sapper from '@sapper/service-worker';

const ASSETS = `cache${sapper.timestamp}`;

// `app.shell` is an array of all the files generated by webpack,
// `app.files` is an array of everything in the `static` directory
const to_cache = sapper.shell.concat(sapper.files);
const cached = new Set(to_cache);

self.addEventListener('install', event => {
event.waitUntil(
caches
.open(ASSETS)
.then(cache => cache.addAll(to_cache))
.then(() => {
self.skipWaiting();
})
);
});

self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(async keys => {
// delete old caches
for (const key of keys) {
if (key !== ASSETS) await caches.delete(key);
}

self.clients.claim();
})
);
});

self.addEventListener('fetch', event => {
if (event.request.method !== 'GET') return;

const url = new URL(event.request.url);

// don't try to handle e.g. data: URIs
if (!url.protocol.startsWith('http')) return;

// ignore dev server requests
if (url.hostname === self.location.hostname && url.port !== self.location.port) return;

// always serve assets and webpack-generated files from cache
if (url.host === self.location.host && cached.has(url.pathname)) {
event.respondWith(caches.match(event.request));
return;
}

// for pages, you might want to serve a shell `index.html` file,
// which Sapper has generated for you. It's not right for every
// app, but if it's right for yours then uncomment this section
/*
event.respondWith(caches.match('/index.html'));
return;
}
*/

if (event.request.cache === 'only-if-cached') return;

// for everything else, try the network first, falling back to
// cache if the user is offline. (If the pages never change, you
// might prefer a cache-first approach to a network-first one.)
event.respondWith(
caches
.open(`offline${sapper.timestamp}`)
.then(async cache => {
try {
const response = await fetch(event.request);
cache.put(event.request, response.clone());
return response;
} catch(err) {
const response = await cache.match(event.request);
if (response) return response;

throw err;
}
})
);
});
Loading

0 comments on commit e7b1aa3

Please sign in to comment.