Compare commits

...

22 Commits

Author SHA1 Message Date
Rich Harris
0fe93cd177 -> v0.0.19 2017-12-15 18:27:04 -05:00
Rich Harris
67fe570f6d dont try to prevent event where none exists 2017-12-15 18:26:55 -05:00
Rich Harris
a3d44aba31 -> v0.0.18 2017-12-15 17:20:36 -05:00
Rich Harris
80ae909b73 serve assets from memory, use caching 2017-12-15 17:20:24 -05:00
Rich Harris
892b18cf80 -> v0.0.17 2017-12-15 16:47:34 -05:00
Rich Harris
0eb96bf01f oops, remove logging 2017-12-15 16:47:29 -05:00
Rich Harris
419f5c5235 -> v0.0.16 2017-12-15 16:46:27 -05:00
Rich Harris
4c61ed5fdd better link click handling, track scroll position 2017-12-15 16:46:11 -05:00
Rich Harris
c19447cf05 -> v0.0.15 2017-12-15 15:29:30 -05:00
Rich Harris
cb2364f476 add noscript message (todo - make it configurable) 2017-12-15 15:29:08 -05:00
Rich Harris
de427d400e -> v0.0.14 2017-12-15 14:49:56 -05:00
Rich Harris
e810ead93f move files around 2017-12-15 14:46:23 -05:00
Rich Harris
f5a19ef34b tweak service worker stuff 2017-12-15 14:43:38 -05:00
Rich Harris
b8c03d330b refactor some webpack stuff, support service worker generation 2017-12-14 15:38:41 -05:00
Rich Harris
6e769496ec -> v0.0.13 2017-12-14 08:23:00 -05:00
Rich Harris
e46aceb2fe implement prefetching anchors with rel=prefetch 2017-12-14 08:21:32 -05:00
Rich Harris
a87cac2481 refactor some stuff 2017-12-14 07:53:17 -05:00
Rich Harris
608fdb7533 -> v0.0.12 2017-12-14 07:15:07 -05:00
Rich Harris
80166b5a7d -> v0.0.11 2017-12-14 07:12:01 -05:00
Rich Harris
24b259f80b fix location, so that runtime can be found from /tmp 2017-12-14 07:11:52 -05:00
Rich Harris
8a9f4bd268 -> v0.0.10 2017-12-14 07:07:47 -05:00
Rich Harris
d940da1a77 serve errors 2017-12-14 07:07:29 -05:00
15 changed files with 424 additions and 306 deletions

View File

@@ -5,10 +5,11 @@ const path = require('path');
const glob = require('glob');
const rimraf = require('rimraf');
const mkdirp = require('mkdirp');
const create_routes = require('./utils/create_routes.js');
const create_templates = require('./utils/create_templates.js');
const create_app = require('./utils/create_app.js');
const create_webpack_compiler = require('./utils/create_webpack_compiler.js');
const create_routes = require('./lib/utils/create_routes.js');
const templates = require('./lib/templates.js');
const create_app = require('./lib/utils/create_app.js');
const create_compiler = require('./lib/utils/create_compiler.js');
const escape_html = require('escape-html');
const { src, dest, dev } = require('./lib/config.js');
const esmRequire = esm(module, {
@@ -25,87 +26,110 @@ module.exports = function connect(opts) {
create_app(src, dest, routes, opts);
const webpack_compiler = create_webpack_compiler(
const compiler = create_compiler(
dest,
routes,
dev
);
const templates = create_templates();
return async function(req, res, next) {
const url = req.url.replace(/\?.+/, '');
if (url.startsWith('/client/')) {
if (url === '/service-worker.js') {
await compiler.ready;
res.set({
'Content-Type': 'application/javascript'
'Content-Type': 'application/javascript',
'Cache-Control': 'max-age=600'
});
fs.createReadStream(`${dest}${url}`).pipe(res);
return;
res.end(compiler.service_worker);
}
// whatever happens, we're going to serve some HTML
res.set({
'Content-Type': 'text/html'
});
else if (url === '/index.html') {
await compiler.ready;
res.set({
'Content-Type': 'text/html',
'Cache-Control': 'max-age=600'
});
res.end(compiler.shell);
}
try {
for (const route of routes) {
if (route.test(url)) {
req.params = route.exec(url);
else if (url.startsWith('/client/')) {
await compiler.ready;
res.set({
'Content-Type': 'application/javascript',
'Cache-Control': 'max-age=31536000'
});
res.end(compiler.asset_cache[url]);
}
const chunk = await webpack_compiler.get_chunk(route.id);
const mod = require(chunk);
else {
// whatever happens, we're going to serve some HTML
res.set({
'Content-Type': 'text/html'
});
if (route.type === 'page') {
const main = await webpack_compiler.client_main;
try {
for (const route of routes) {
if (route.test(url)) {
await compiler.ready;
let data = { params: req.params, query: req.query };
if (mod.default.preload) data = Object.assign(data, await mod.default.preload(data));
req.params = route.exec(url);
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, {
main,
html,
head: `<noscript id='sapper-head-start'></noscript>${head}<noscript id='sapper-head-end'></noscript>`,
styles: (css && css.code ? `<style>${css.code}</style>` : '')
});
if (route.type === 'page') {
let data = { params: req.params, query: req.query };
if (mod.default.preload) data = Object.assign(data, await mod.default.preload(data));
res.status(200);
res.end(page);
}
const { html, head, css } = mod.default.render(data);
else {
const handler = mod[req.method.toLowerCase()];
if (handler) {
if (handler.length === 2) {
handler(req, res);
} else {
const data = await handler(req);
const page = templates.render(200, {
main: compiler.client_main,
html,
head: `<noscript id='sapper-head-start'></noscript>${head}<noscript id='sapper-head-end'></noscript>`,
styles: (css && css.code ? `<style>${css.code}</style>` : '')
});
// TODO headers, error handling
if (typeof data === 'string') {
res.end(data);
res.status(200);
res.end(page);
}
else {
const handler = mod[req.method.toLowerCase()];
if (handler) {
if (handler.length === 2) {
handler(req, res);
} 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, {
status: 404,
url
}));
} catch(err) {
// TODO nice error pages
res.status(500);
res.end(err ? (err.stack || err.message || err) : 'Unknown error');
res.status(404).end(templates.render(404, {
title: 'Not found',
status: 404,
method: req.method,
url
}));
} catch(err) {
res.status(500).end(templates.render(500, {
title: err.name || 'Internal server error',
url,
error: escape_html(err.details || err.message || err || 'Unknown error')
}));
}
}
};
};

View File

@@ -1,5 +1,5 @@
const glob = require('glob');
const create_routes = require('../utils/create_routes.js');
const create_routes = require('./utils/create_routes.js');
const { src } = require('./config.js');
const route_manager = {

43
lib/templates.js Normal file
View File

@@ -0,0 +1,43 @@
const fs = require('fs');
const glob = require('glob');
const templates = glob.sync('*.html', { cwd: 'templates' })
.map(file => {
const template = fs.readFileSync(`templates/${file}`, 'utf-8');
const status = file.replace('.html', '').toLowerCase();
if (!/^[0-9x]{3}$/.test(status)) {
throw new Error(`Bad template — should be a valid status code like 404.html, or a wildcard like 2xx.html`);
}
const specificity = (
(status[0] === 'x' ? 0 : 4) +
(status[1] === 'x' ? 0 : 2) +
(status[2] === 'x' ? 0 : 1)
);
const pattern = new RegExp(`^${status.split('').map(d => d === 'x' ? '\\d' : d).join('')}$`);
return {
test: status => pattern.test(status),
specificity,
render(data) {
return template.replace(/%sapper\.(\w+)%/g, (match, key) => {
return key in data ? data[key] : '';
});
}
}
})
.sort((a, b) => b.specificity - a.specificity);
exports.render = (status, data) => {
const template = templates.find(template => template.test(status));
if (template) return template.render(data);
return `Missing template for status code ${status}`;
};
exports.onchange = fn => {
// TODO in dev mode, keep this updated, and allow
// webpack compiler etc to hook into it
};

26
lib/utils/create_app.js Normal file
View File

@@ -0,0 +1,26 @@
const fs = require('fs');
const path = require('path');
const template = fs.readFileSync(path.resolve(__dirname, '../../templates/main.js'), 'utf-8');
module.exports = function create_app(src, dest, routes, options) {
// TODO in dev mode, watch files
const code = routes
.filter(route => route.type === 'page')
.map(route => {
const params = route.dynamic.length === 0 ?
'{}' :
`{ ${route.dynamic.map((part, i) => `${part}: match[${i + 1}]`).join(', ') } }`;
return `{ pattern: ${route.pattern}, params: match => (${params}), load: () => import(/* webpackChunkName: "${route.id}" */ '${src}/${route.file}') }`
})
.join(',\n\t');
const main = template
.replace('__app__', path.resolve(__dirname, '../../runtime/app.js'))
.replace('__selector__', options.selector || 'main')
.replace('__routes__', code);
fs.writeFileSync(path.join(dest, 'main.js'), main);
};

View File

@@ -0,0 +1,104 @@
const fs = require('fs');
const path = require('path');
const glob = require('glob');
const webpack = require('webpack');
const templates = require('../templates.js');
module.exports = function create_webpack_compiler(dest, routes, dev) {
const compiler = {};
const client = webpack(
require(path.resolve('webpack.client.config.js'))
);
const server = webpack(
require(path.resolve('webpack.server.config.js'))
);
if (false) { // TODO watch in dev
// TODO how can we invalidate compiler.client_main when watcher restarts?
compiler.client_main = new Promise((fulfil, reject) => {
client.watch({}, (err, stats) => {
if (err || stats.hasErrors()) {
// TODO handle errors
}
const filename = stats.toJson().assetsByChunkName.main;
fulfil(`/client/${filename}`);
});
});
// TODO server
} else {
compiler.ready = Promise.all([
new Promise((fulfil, reject) => {
client.run((err, stats) => {
console.log(stats.toString({ colors: true }));
const info = stats.toJson();
if (err || stats.hasErrors()) {
reject(err || info.errors[0]);
}
compiler.client_main = `/client/${info.assetsByChunkName.main}`;
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();
});
}),
new Promise((fulfil, reject) => {
server.run((err, stats) => {
console.log(stats.toString({ colors: true }));
const info = stats.toJson();
if (err || stats.hasErrors()) {
reject(err || info.errors[0]);
}
compiler.chunks = info.assetsByChunkName;
fulfil();
});
})
]).then(() => {
const assets = glob.sync('**', { cwd: 'assets' });
const route_code = `[${
routes
.filter(route => route.type === 'page')
.map(route => `{ pattern: ${route.pattern} }`)
.join(', ')
}]`;
compiler.service_worker = fs.readFileSync('templates/service-worker.js', 'utf-8')
.replace('__timestamp__', Date.now())
.replace('__assets__', JSON.stringify(assets))
.replace('__shell__', JSON.stringify(compiler.assets.concat('/index.html')))
.replace('__routes__', route_code);
compiler.shell = templates.render(200, {
styles: '',
head: '',
html: '<noscript>Please enable JavaScript!</noscript>',
main: compiler.client_main
});
// 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 => {
return path.resolve(dest, 'server', compiler.chunks[id]);
};
}
return compiler;
};

53
package-lock.json generated
View File

@@ -1,6 +1,6 @@
{
"name": "sapper",
"version": "0.0.3",
"version": "0.0.9",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
@@ -578,6 +578,11 @@
"es6-symbol": "3.1.1"
}
},
"escape-html": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
"integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg="
},
"escape-string-regexp": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz",
@@ -670,18 +675,6 @@
"is-extglob": "1.0.0"
}
},
"extract-text-webpack-plugin": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/extract-text-webpack-plugin/-/extract-text-webpack-plugin-3.0.2.tgz",
"integrity": "sha512-bt/LZ4m5Rqt/Crl2HiKuAl/oqg0psx1tsTLkvWbJen1CtD+fftkZhMaQ9HOtY2gWsl2Wq+sABmMVi9z3DhKWQQ==",
"dev": true,
"requires": {
"async": "2.6.0",
"loader-utils": "1.1.0",
"schema-utils": "0.3.0",
"webpack-sources": "1.1.0"
}
},
"fast-deep-equal": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-1.0.0.tgz",
@@ -2095,12 +2088,6 @@
"mem": "1.1.0"
}
},
"os-tmpdir": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz",
"integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=",
"dev": true
},
"p-finally": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz",
@@ -2413,15 +2400,6 @@
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.1.tgz",
"integrity": "sha512-kKvNJn6Mm93gAczWVJg7wH+wGYWNrDHdWvpUmHyEsgCtIwwo3bqPtV4tR5tuPaUhTOo/kvhVwd8XwwOllGYkbg=="
},
"schema-utils": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-0.3.0.tgz",
"integrity": "sha1-9YdyIs4+kx7a4DnxfrNxbnE3+M8=",
"dev": true,
"requires": {
"ajv": "5.5.1"
}
},
"semver": {
"version": "5.4.1",
"resolved": "https://registry.npmjs.org/semver/-/semver-5.4.1.tgz",
@@ -2587,16 +2565,6 @@
"integrity": "sha512-xRw4pjF19XKfeTxp+TOTE/MQmRS7tRzm0hhh0dr/nc3NuHBfCBXnfve0ZymF8tZ+J/WM0cqfZ83RxZid2zf7qA==",
"dev": true
},
"svelte-loader": {
"version": "2.2.1",
"resolved": "https://registry.npmjs.org/svelte-loader/-/svelte-loader-2.2.1.tgz",
"integrity": "sha512-SNdEPwLpoWqKMk5wjJUVd7LUFK9rQoMPxQ8uJoszWSgTpbYICSnxFCEDvhDvcHbmAFSOOXnoJAdvoCTnBw3+kg==",
"dev": true,
"requires": {
"loader-utils": "1.1.0",
"tmp": "0.0.31"
}
},
"tapable": {
"version": "0.2.8",
"resolved": "https://registry.npmjs.org/tapable/-/tapable-0.2.8.tgz",
@@ -2610,15 +2578,6 @@
"setimmediate": "1.0.5"
}
},
"tmp": {
"version": "0.0.31",
"resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.31.tgz",
"integrity": "sha1-jzirlDjhcxXl29izZX6L+yd65Kc=",
"dev": true,
"requires": {
"os-tmpdir": "1.0.2"
}
},
"to-arraybuffer": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/to-arraybuffer/-/to-arraybuffer-1.0.1.tgz",

View File

@@ -1,6 +1,6 @@
{
"name": "sapper",
"version": "0.0.9",
"version": "0.0.19",
"description": "Combat-ready apps, engineered by Svelte",
"main": "connect.js",
"directories": {
@@ -8,6 +8,7 @@
},
"dependencies": {
"@std/esm": "^0.18.0",
"escape-html": "^1.0.3",
"mkdirp": "^0.5.1",
"rimraf": "^2.6.2",
"webpack": "^3.10.0"

View File

@@ -1,22 +1,170 @@
const detach = node => {
node.parentNode.removeChild(node);
};
let component;
const scroll_history = {};
let uid = 1;
let cid;
window.scroll_history = scroll_history;
if ('scrollRestoration' in history) {
history.scrollRestoration = 'manual'
}
const app = {
init(callback) {
init(target, routes) {
function select_route(url) {
if (url.origin !== window.location.origin) return null;
for (const route of routes) {
const match = route.pattern.exec(url.pathname);
if (match) {
const params = route.params(match);
const query = {};
for (const [key, value] of url.searchParams) query[key] = value || true;
return { route, data: { params, query } };
}
}
}
function render(Component, data, scroll) {
Promise.resolve(
Component.preload ? Component.preload(data) : {}
).then(preloaded => {
if (component) {
component.destroy();
} else {
// first load — remove SSR'd <head> contents
const start = document.querySelector('#sapper-head-start');
let end = document.querySelector('#sapper-head-end');
if (start && end) {
while (start.nextSibling !== end) detach(start.nextSibling);
detach(start);
detach(end);
}
// preload additional routes
routes.reduce((promise, route) => promise.then(route.load), Promise.resolve());
}
component = new Component({
target,
data: Object.assign(data, preloaded),
hydrate: !!component
});
window.scrollTo(scroll.x, scroll.y);
});
}
function navigate(url, id) {
const selected = select_route(url);
if (selected) {
if (id) {
// popstate or initial navigation
cid = id;
} else {
// clicked on a link. preserve scroll state
scroll_history[cid] = scroll_state();
id = cid = ++uid;
scroll_history[cid] = { x: 0, y: 0 };
history.pushState({ id }, '', url.href);
}
selected.route.load().then(mod => {
render(mod.default, selected.data, scroll_history[id]);
});
cid = id;
return true;
}
}
function findAnchor(node) {
while (node && node.nodeName.toUpperCase() !== 'A') node = node.parentNode; // SVG <a> elements have a lowercase name
return node;
}
window.addEventListener('click', event => {
let a = event.target;
while (a && a.nodeName !== 'A') a = a.parentNode;
// Adapted from https://github.com/visionmedia/page.js
// MIT license https://github.com/visionmedia/page.js#license
if (which(event) !== 1) return;
if (event.metaKey || event.ctrlKey || event.shiftKey) return;
if (event.defaultPrevented) return;
const a = findAnchor(event.target);
if (!a) return;
if (callback(new URL(a.href))) {
event.preventDefault();
// check if link is inside an svg
// in this case, both href and target are always inside an object
const svg = typeof a.href === 'object' && a.href.constructor.name === 'SVGAnimatedString';
const href = svg ? a.href.baseVal : a.href;
// Ignore if tag has
// 1. 'download' attribute
// 2. rel='external' attribute
if (a.hasAttribute('download') || a.getAttribute('rel') === 'external') return;
// Ignore if <a> has a target
if (svg ? a.target.baseVal : a.target) return;
const scroll = scroll_state();
if (navigate(new URL(a.href), null)) {
event.preventDefault();
history.pushState({}, '', a.href);
}
});
function preload(event) {
const a = findAnchor(event.target);
if (!a || a.rel !== 'prefetch') return;
const selected = select_route(new URL(a.href));
if (selected) {
selected.route.load().then(mod => {
if (mod.default.preload) mod.default.preload(selected.data);
});
}
}
window.addEventListener('touchstart', preload);
window.addEventListener('mouseover', preload);
window.addEventListener('popstate', event => {
callback(window.location);
if (!event.state) return; // hashchange, or otherwise outside sapper's control
scroll_history[cid] = scroll_state();
navigate(new URL(window.location), event.state.id);
});
callback(window.location);
const scroll = scroll_history[uid] = scroll_state();
history.replaceState({ id: uid }, '', window.location.href);
navigate(new URL(window.location), uid);
}
};
function which(event) {
event = event || window.event;
return event.which === null ? event.button : event.which;
}
function scroll_state() {
return {
x: window.scrollX,
y: window.scrollY
};
}
export default app;

View File

@@ -1,47 +1,5 @@
import app from 'sapper/runtime/app.js';
import { detachNode } from 'svelte/shared.js';
import app from '__app__';
const target = document.querySelector('__selector__');
let component;
app.init(url => {
if (url.origin !== window.location.origin) return;
let match;
let params = {};
const query = {};
function render(mod) {
const route = { query, params };
Promise.resolve(
mod.default.preload ? mod.default.preload(route) : {}
).then(preloaded => {
if (component) {
component.destroy();
} else {
// remove SSR'd <head> contents
const start = document.querySelector('#sapper-head-start');
let end = document.querySelector('#sapper-head-end');
if (start && end) {
while (start.nextSibling !== end) detachNode(start.nextSibling);
detachNode(start);
detachNode(end);
}
target.innerHTML = '';
}
component = new mod.default({
target,
data: Object.assign(route, preloaded),
hydrate: !!component
});
});
}
// ROUTES
return true;
});
app.init(document.querySelector('__selector__'), [
__routes__
]);

View File

@@ -1,41 +0,0 @@
const fs = require('fs');
const path = require('path');
const template = fs.readFileSync(path.resolve(__dirname, '../templates/main.js'), 'utf-8');
module.exports = function create_app(src, dest, routes, options) {
// TODO in dev mode, watch files
const code = routes
.filter(route => route.type === 'page')
.map(route => {
const condition = route.dynamic.length === 0 ?
`url.pathname === '/${route.parts.join('/')}'` :
`match = ${route.pattern}.exec(url.pathname)`;
const lines = [];
route.dynamic.forEach((part, i) => {
lines.push(
`params.${part} = match[${i + 1}];`
);
});
lines.push(
`import('${src}/${route.file}').then(render);`
);
return `
if (${condition}) {
${lines.join(`\n\t\t\t\t\t`)}
}
`.replace(/^\t{3}/gm, '').trim();
})
.join(' else ') + ' else return false;';
const main = template
.replace('__selector__', options.selector || 'main')
.replace('// ROUTES', code);
fs.writeFileSync(path.join(dest, 'main.js'), main);
};

View File

@@ -1,42 +0,0 @@
const fs = require('fs');
const glob = require('glob');
module.exports = function create_templates() {
const templates = glob.sync('*.html', { cwd: 'templates' })
.map(file => {
const template = fs.readFileSync(`templates/${file}`, 'utf-8');
const status = file.replace('.html', '').toLowerCase();
if (!/^[0-9x]{3}$/.test(status)) {
throw new Error(`Bad template — should be a valid status code like 404.html, or a wildcard like 2xx.html`);
}
const specificity = (
(status[0] === 'x' ? 0 : 4) +
(status[1] === 'x' ? 0 : 2) +
(status[2] === 'x' ? 0 : 1)
);
const pattern = new RegExp(`^${status.split('').map(d => d === 'x' ? '\\d' : d).join('')}$`);
return {
test: status => pattern.test(status),
specificity,
render(data) {
return template.replace(/%sapper\.(\w+)%/g, (match, key) => {
return key in data ? data[key] : '';
});
}
}
})
.sort((a, b) => b.specificity - a.specificity);
return {
render: (status, data) => {
const template = templates.find(template => template.test(status));
if (template) return template.render(data);
return `Missing template for status code ${status}`;
}
};
};

View File

@@ -1,62 +0,0 @@
const fs = require('fs');
const path = require('path');
const webpack = require('webpack');
module.exports = function create_webpack_compiler(out, routes, dev) {
const compiler = {};
const client = webpack(
require(path.resolve('webpack.client.config.js'))
);
const server = webpack(
require(path.resolve('webpack.server.config.js'))
);
if (false) { // TODO watch in dev
// TODO how can we invalidate compiler.client_main when watcher restarts?
compiler.client_main = new Promise((fulfil, reject) => {
client.watch({}, (err, stats) => {
if (err || stats.hasErrors()) {
// TODO handle errors
}
const filename = stats.toJson().assetsByChunkName.main;
fulfil(`/client/${filename}`);
});
});
// TODO server
} else {
compiler.client_main = new Promise((fulfil, reject) => {
client.run((err, stats) => {
if (err || stats.hasErrors()) {
console.log(stats.toString({ colors: true }));
reject(err);
}
const filename = stats.toJson().assetsByChunkName.main;
fulfil(`/client/${filename}`);
});
});
const chunks = new Promise((fulfil, reject) => {
server.run((err, stats) => {
if (err || stats.hasErrors()) {
// TODO deal with hasErrors
console.log(stats.toString({ colors: true }));
reject(err);
}
fulfil(stats.toJson().assetsByChunkName);
});
});
compiler.get_chunk = async id => {
const assetsByChunkName = await chunks;
return path.resolve(out, 'server', assetsByChunkName[id]);
};
}
return compiler;
};

View File

@@ -16,7 +16,7 @@ module.exports = {
return {
path: `${dest}/client`,
filename: '[name].[hash].js',
chunkFilename: '[name].[id].js',
chunkFilename: '[name].[id].[hash].js',
publicPath: '/client/'
};
}
@@ -35,7 +35,7 @@ module.exports = {
return {
path: `${dest}/server`,
filename: '[name].[hash].js',
chunkFilename: '[name].[id].js',
chunkFilename: '[name].[id].[hash].js',
libraryTarget: 'commonjs2'
};
}