mirror of
https://github.com/kevin-DL/sapper.git
synced 2026-01-15 12:24:47 +00:00
Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0fe93cd177 | ||
|
|
67fe570f6d | ||
|
|
a3d44aba31 | ||
|
|
80ae909b73 | ||
|
|
892b18cf80 | ||
|
|
0eb96bf01f |
134
connect.js
134
connect.js
@@ -8,7 +8,7 @@ const mkdirp = require('mkdirp');
|
|||||||
const create_routes = require('./lib/utils/create_routes.js');
|
const create_routes = require('./lib/utils/create_routes.js');
|
||||||
const templates = require('./lib/templates.js');
|
const templates = require('./lib/templates.js');
|
||||||
const create_app = require('./lib/utils/create_app.js');
|
const create_app = require('./lib/utils/create_app.js');
|
||||||
const create_webpack_compiler = require('./lib/utils/create_webpack_compiler.js');
|
const create_compiler = require('./lib/utils/create_compiler.js');
|
||||||
const escape_html = require('escape-html');
|
const escape_html = require('escape-html');
|
||||||
const { src, dest, dev } = require('./lib/config.js');
|
const { src, dest, dev } = require('./lib/config.js');
|
||||||
|
|
||||||
@@ -26,7 +26,7 @@ module.exports = function connect(opts) {
|
|||||||
|
|
||||||
create_app(src, dest, routes, opts);
|
create_app(src, dest, routes, opts);
|
||||||
|
|
||||||
const webpack_compiler = create_webpack_compiler(
|
const compiler = create_compiler(
|
||||||
dest,
|
dest,
|
||||||
routes,
|
routes,
|
||||||
dev
|
dev
|
||||||
@@ -35,81 +35,101 @@ module.exports = function connect(opts) {
|
|||||||
return async function(req, res, next) {
|
return async function(req, res, next) {
|
||||||
const url = req.url.replace(/\?.+/, '');
|
const url = req.url.replace(/\?.+/, '');
|
||||||
|
|
||||||
if (url === '/service-worker.js' || url === '/index.html' || url.startsWith('/client/')) {
|
if (url === '/service-worker.js') {
|
||||||
await webpack_compiler.ready;
|
await compiler.ready;
|
||||||
res.set({
|
res.set({
|
||||||
'Content-Type': url === '/index.html' ? 'text/html' : 'application/javascript'
|
'Content-Type': 'application/javascript',
|
||||||
|
'Cache-Control': 'max-age=600'
|
||||||
});
|
});
|
||||||
fs.createReadStream(`${dest}${url}`).pipe(res);
|
res.end(compiler.service_worker);
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// whatever happens, we're going to serve some HTML
|
else if (url === '/index.html') {
|
||||||
res.set({
|
await compiler.ready;
|
||||||
'Content-Type': 'text/html'
|
res.set({
|
||||||
});
|
'Content-Type': 'text/html',
|
||||||
|
'Cache-Control': 'max-age=600'
|
||||||
|
});
|
||||||
|
res.end(compiler.shell);
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
else if (url.startsWith('/client/')) {
|
||||||
for (const route of routes) {
|
await compiler.ready;
|
||||||
if (route.test(url)) {
|
res.set({
|
||||||
await webpack_compiler.ready;
|
'Content-Type': 'application/javascript',
|
||||||
|
'Cache-Control': 'max-age=31536000'
|
||||||
|
});
|
||||||
|
res.end(compiler.asset_cache[url]);
|
||||||
|
}
|
||||||
|
|
||||||
req.params = route.exec(url);
|
else {
|
||||||
|
// whatever happens, we're going to serve some HTML
|
||||||
|
res.set({
|
||||||
|
'Content-Type': 'text/html'
|
||||||
|
});
|
||||||
|
|
||||||
const chunk = webpack_compiler.chunks[route.id];
|
try {
|
||||||
const mod = require(path.resolve(dest, 'server', chunk));
|
for (const route of routes) {
|
||||||
|
if (route.test(url)) {
|
||||||
|
await compiler.ready;
|
||||||
|
|
||||||
if (route.type === 'page') {
|
req.params = route.exec(url);
|
||||||
let data = { params: req.params, query: req.query };
|
|
||||||
if (mod.default.preload) data = Object.assign(data, await mod.default.preload(data));
|
|
||||||
|
|
||||||
const { html, head, css } = mod.default.render(data);
|
const chunk = compiler.chunks[route.id];
|
||||||
|
const mod = require(path.resolve(dest, 'server', chunk));
|
||||||
|
|
||||||
const page = templates.render(200, {
|
if (route.type === 'page') {
|
||||||
main: webpack_compiler.client_main,
|
let data = { params: req.params, query: req.query };
|
||||||
html,
|
if (mod.default.preload) data = Object.assign(data, await mod.default.preload(data));
|
||||||
head: `<noscript id='sapper-head-start'></noscript>${head}<noscript id='sapper-head-end'></noscript>`,
|
|
||||||
styles: (css && css.code ? `<style>${css.code}</style>` : '')
|
|
||||||
});
|
|
||||||
|
|
||||||
res.status(200);
|
const { html, head, css } = mod.default.render(data);
|
||||||
res.end(page);
|
|
||||||
}
|
|
||||||
|
|
||||||
else {
|
const page = templates.render(200, {
|
||||||
const handler = mod[req.method.toLowerCase()];
|
main: compiler.client_main,
|
||||||
if (handler) {
|
html,
|
||||||
if (handler.length === 2) {
|
head: `<noscript id='sapper-head-start'></noscript>${head}<noscript id='sapper-head-end'></noscript>`,
|
||||||
handler(req, res);
|
styles: (css && css.code ? `<style>${css.code}</style>` : '')
|
||||||
} else {
|
});
|
||||||
const data = await handler(req);
|
|
||||||
|
|
||||||
// TODO headers, error handling
|
res.status(200);
|
||||||
if (typeof data === 'string') {
|
res.end(page);
|
||||||
res.end(data);
|
}
|
||||||
|
|
||||||
|
else {
|
||||||
|
const handler = mod[req.method.toLowerCase()];
|
||||||
|
if (handler) {
|
||||||
|
if (handler.length === 2) {
|
||||||
|
handler(req, res);
|
||||||
} else {
|
} else {
|
||||||
res.end(JSON.stringify(data));
|
const data = await handler(req);
|
||||||
|
|
||||||
|
// TODO headers, error handling
|
||||||
|
if (typeof data === 'string') {
|
||||||
|
res.end(data);
|
||||||
|
} else {
|
||||||
|
res.end(JSON.stringify(data));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
res.status(404).end(templates.render(404, {
|
res.status(404).end(templates.render(404, {
|
||||||
title: 'Not found',
|
title: 'Not found',
|
||||||
status: 404,
|
status: 404,
|
||||||
method: req.method,
|
method: req.method,
|
||||||
url
|
url
|
||||||
}));
|
}));
|
||||||
} catch(err) {
|
} catch(err) {
|
||||||
res.status(500).end(templates.render(500, {
|
res.status(500).end(templates.render(500, {
|
||||||
title: err.name || 'Internal server error',
|
title: err.name || 'Internal server error',
|
||||||
url,
|
url,
|
||||||
error: escape_html(err.details || err.message || err || 'Unknown error')
|
error: escape_html(err.details || err.message || err || 'Unknown error')
|
||||||
}));
|
}));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
@@ -13,7 +13,7 @@ module.exports = function create_app(src, dest, routes, options) {
|
|||||||
'{}' :
|
'{}' :
|
||||||
`{ ${route.dynamic.map((part, i) => `${part}: match[${i + 1}]`).join(', ') } }`;
|
`{ ${route.dynamic.map((part, i) => `${part}: match[${i + 1}]`).join(', ') } }`;
|
||||||
|
|
||||||
return `{ pattern: ${route.pattern}, params: match => (${params}), load: () => import('${src}/${route.file}') }`
|
return `{ pattern: ${route.pattern}, params: match => (${params}), load: () => import(/* webpackChunkName: "${route.id}" */ '${src}/${route.file}') }`
|
||||||
})
|
})
|
||||||
.join(',\n\t');
|
.join(',\n\t');
|
||||||
|
|
||||||
|
|||||||
@@ -44,6 +44,11 @@ module.exports = function create_webpack_compiler(dest, routes, dev) {
|
|||||||
compiler.client_main = `/client/${info.assetsByChunkName.main}`;
|
compiler.client_main = `/client/${info.assetsByChunkName.main}`;
|
||||||
compiler.assets = info.assets.map(asset => `/client/${asset.name}`);
|
compiler.assets = info.assets.map(asset => `/client/${asset.name}`);
|
||||||
|
|
||||||
|
compiler.asset_cache = {};
|
||||||
|
compiler.assets.forEach(file => {
|
||||||
|
compiler.asset_cache[file] = fs.readFileSync(path.join(dest, file), 'utf-8');
|
||||||
|
});
|
||||||
|
|
||||||
fulfil();
|
fulfil();
|
||||||
});
|
});
|
||||||
}),
|
}),
|
||||||
@@ -59,7 +64,6 @@ module.exports = function create_webpack_compiler(dest, routes, dev) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
compiler.chunks = info.assetsByChunkName;
|
compiler.chunks = info.assetsByChunkName;
|
||||||
|
|
||||||
fulfil();
|
fulfil();
|
||||||
});
|
});
|
||||||
})
|
})
|
||||||
@@ -73,22 +77,22 @@ module.exports = function create_webpack_compiler(dest, routes, dev) {
|
|||||||
.join(', ')
|
.join(', ')
|
||||||
}]`;
|
}]`;
|
||||||
|
|
||||||
const service_worker = fs.readFileSync('templates/service-worker.js', 'utf-8')
|
compiler.service_worker = fs.readFileSync('templates/service-worker.js', 'utf-8')
|
||||||
.replace('__timestamp__', Date.now())
|
.replace('__timestamp__', Date.now())
|
||||||
.replace('__assets__', JSON.stringify(assets))
|
.replace('__assets__', JSON.stringify(assets))
|
||||||
.replace('__shell__', JSON.stringify(compiler.assets.concat('/index.html')))
|
.replace('__shell__', JSON.stringify(compiler.assets.concat('/index.html')))
|
||||||
.replace('__routes__', route_code);
|
.replace('__routes__', route_code);
|
||||||
|
|
||||||
fs.writeFileSync(path.resolve(dest, 'service-worker.js'), service_worker);
|
compiler.shell = templates.render(200, {
|
||||||
|
|
||||||
const shell = templates.render(200, {
|
|
||||||
styles: '',
|
styles: '',
|
||||||
head: '',
|
head: '',
|
||||||
html: '<noscript>Please enable JavaScript!</noscript>',
|
html: '<noscript>Please enable JavaScript!</noscript>',
|
||||||
main: compiler.client_main
|
main: compiler.client_main
|
||||||
});
|
});
|
||||||
|
|
||||||
fs.writeFileSync(path.resolve(dest, 'index.html'), shell);
|
// useful for debugging, but the files are served from memory
|
||||||
|
fs.writeFileSync(path.resolve(dest, 'service-worker.js'), compiler.service_worker);
|
||||||
|
fs.writeFileSync(path.resolve(dest, 'index.html'), compiler.shell);
|
||||||
});
|
});
|
||||||
|
|
||||||
compiler.get_chunk = async id => {
|
compiler.get_chunk = async id => {
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "sapper",
|
"name": "sapper",
|
||||||
"version": "0.0.16",
|
"version": "0.0.19",
|
||||||
"description": "Combat-ready apps, engineered by Svelte",
|
"description": "Combat-ready apps, engineered by Svelte",
|
||||||
"main": "connect.js",
|
"main": "connect.js",
|
||||||
"directories": {
|
"directories": {
|
||||||
|
|||||||
@@ -77,7 +77,6 @@ const app = {
|
|||||||
scroll_history[cid] = { x: 0, y: 0 };
|
scroll_history[cid] = { x: 0, y: 0 };
|
||||||
|
|
||||||
history.pushState({ id }, '', url.href);
|
history.pushState({ id }, '', url.href);
|
||||||
event.preventDefault();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
selected.route.load().then(mod => {
|
selected.route.load().then(mod => {
|
||||||
@@ -121,7 +120,9 @@ const app = {
|
|||||||
|
|
||||||
const scroll = scroll_state();
|
const scroll = scroll_state();
|
||||||
|
|
||||||
navigate(new URL(a.href), null);
|
if (navigate(new URL(a.href), null)) {
|
||||||
|
event.preventDefault();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
function preload(event) {
|
function preload(event) {
|
||||||
@@ -144,8 +145,6 @@ const app = {
|
|||||||
if (!event.state) return; // hashchange, or otherwise outside sapper's control
|
if (!event.state) return; // hashchange, or otherwise outside sapper's control
|
||||||
scroll_history[cid] = scroll_state();
|
scroll_history[cid] = scroll_state();
|
||||||
|
|
||||||
console.log(`storing current scroll: ${cid}`, scroll_state());
|
|
||||||
console.log(`navigating to state: ${event.state.id}`, scroll_history[event.state.id]);
|
|
||||||
navigate(new URL(window.location), event.state.id);
|
navigate(new URL(window.location), event.state.id);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ module.exports = {
|
|||||||
return {
|
return {
|
||||||
path: `${dest}/client`,
|
path: `${dest}/client`,
|
||||||
filename: '[name].[hash].js',
|
filename: '[name].[hash].js',
|
||||||
chunkFilename: '[name].[id].js',
|
chunkFilename: '[name].[id].[hash].js',
|
||||||
publicPath: '/client/'
|
publicPath: '/client/'
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -35,7 +35,7 @@ module.exports = {
|
|||||||
return {
|
return {
|
||||||
path: `${dest}/server`,
|
path: `${dest}/server`,
|
||||||
filename: '[name].[hash].js',
|
filename: '[name].[hash].js',
|
||||||
chunkFilename: '[name].[id].js',
|
chunkFilename: '[name].[id].[hash].js',
|
||||||
libraryTarget: 'commonjs2'
|
libraryTarget: 'commonjs2'
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user