Compare commits

..

14 Commits

Author SHA1 Message Date
Rich Harris
9a5d273590 -> v0.9.4 2018-03-11 19:00:39 -04:00
Rich Harris
3816fe71ad Merge pull request #196 from sveltejs/gh-186
implement --open
2018-03-11 16:52:41 -04:00
Rich Harris
69f5b9cac7 implement --open - fixes #186 2018-03-11 16:01:13 -04:00
Rich Harris
ad14320dc3 Merge pull request #195 from sveltejs/export-logs
show which files are being exported
2018-03-11 15:50:13 -04:00
Rich Harris
43563bd8e5 show which files are being exported 2018-03-11 15:44:53 -04:00
Rich Harris
02d558b97c Merge pull request #194 from sveltejs/gh-172
minify HTML on export
2018-03-11 15:19:07 -04:00
Rich Harris
866286c95e minify HTML on export 2018-03-11 14:57:10 -04:00
Rich Harris
e1b5e336dc Merge pull request #193 from sveltejs/gh-15
minify HTML templates
2018-03-11 14:14:39 -04:00
Rich Harris
1d71b86c0f remove all hard-coded locations (#181) 2018-03-11 13:43:11 -04:00
Rich Harris
bdc248f09a minify HTML at build time (also fixes #181) 2018-03-11 13:35:29 -04:00
Rich Harris
be63ea7c96 add SAPPER_BASE and SAPPER_APP environment variables 2018-03-11 13:29:39 -04:00
Rich Harris
819ec0b776 minify HTML templates - fixes #15 2018-03-11 13:10:43 -04:00
Rich Harris
d22d37fb18 Merge pull request #192 from sveltejs/misc-tidy-up
a few small tweaks
2018-03-11 13:10:15 -04:00
Rich Harris
8ec433581a a few small tweaks 2018-03-11 12:54:35 -04:00
18 changed files with 161 additions and 114 deletions

View File

@@ -1,5 +1,13 @@
# sapper changelog
## 0.9.4
* Add `SAPPER_BASE` and `SAPPER_APP` environment variables ([#181](https://github.com/sveltejs/sapper/issues/181))
* Minify template in `sapper build` ([#15](https://github.com/sveltejs/sapper/issues/15))
* Minify all HTML files in `sapper export` ([#172](https://github.com/sveltejs/sapper/issues/172))
* Log exported files ([#195](https://github.com/sveltejs/sapper/pull/195))
* Add `--open`/`-o` flag to `sapper dev` and `sapper start` ([#186](https://github.com/sveltejs/sapper/issues/186))
## 0.9.3
* Fix path to `sapper-dev-client`

View File

@@ -1,2 +0,0 @@
// TODO write to this file, instead of middleware.ts.js
module.exports = require('./dist/middleware.ts.js');

View File

@@ -1,8 +1,8 @@
{
"name": "sapper",
"version": "0.9.3",
"version": "0.9.4",
"description": "Military-grade apps, engineered by Svelte",
"main": "middleware.js",
"main": "dist/middleware.ts.js",
"bin": {
"sapper": "./sapper"
},
@@ -23,10 +23,12 @@
"clorox": "^1.0.3",
"devalue": "^1.0.1",
"glob": "^7.1.2",
"html-minifier": "^3.5.10",
"mkdirp": "^0.5.1",
"node-fetch": "^1.7.3",
"polka": "^0.3.4",
"port-authority": "^1.0.0",
"port-authority": "^1.0.2",
"pretty-bytes": "^4.0.2",
"pretty-ms": "^3.1.0",
"require-relative": "^0.8.7",
"rimraf": "^2.6.2",

View File

@@ -13,7 +13,8 @@ const prog = sade('sapper').version(pkg.version);
prog.command('dev')
.describe('Start a development server')
.option('-p, --port', 'Specify a port')
.action(async (opts: { port: number }) => {
.option('-o, --open', 'Open a browser window')
.action(async (opts: { port: number, open: boolean }) => {
const { dev } = await import('./cli/dev');
dev(opts);
});
@@ -40,7 +41,8 @@ prog.command('build [dest]')
prog.command('start [dir]')
.describe('Start your app')
.option('-p, --port', 'Specify a port')
.action(async (dir = 'build', opts: { port: number }) => {
.option('-o, --open', 'Open a browser window')
.action(async (dir = 'build', opts: { port: number, open: boolean }) => {
const { start } = await import('./cli/start');
start(dir, opts);
});
@@ -58,7 +60,7 @@ prog.command('export [dest]')
try {
const { build } = await import('./cli/build');
await build();
console.error(`\n> Built in ${elapsed(start)}. Exporting...`);
console.error(`\n> Built in ${elapsed(start)}. Crawling site...`);
const { exporter } = await import('./cli/export');
await exporter(dest);

View File

@@ -3,11 +3,12 @@ import * as path from 'path';
import * as clorox from 'clorox';
import mkdirp from 'mkdirp';
import rimraf from 'rimraf';
import { create_compilers, create_app, create_routes, create_serviceworker } from '../core'
import { src, dest, dev } from '../config';
import { minify_html } from './utils/minify_html';
import { create_compilers, create_main_manifests, create_routes, create_serviceworker_manifest } from '../core'
import { locations } from '../config';
export async function build() {
const output = dest();
const output = locations.dest();
mkdirp.sync(output);
rimraf.sync(path.join(output, '**/*'));
@@ -15,7 +16,7 @@ export async function build() {
const routes = create_routes();
// create app/manifest/client.js and app/manifest/server.js
create_app({ routes, src, dev });
create_main_manifests({ routes });
const { client, server, serviceworker } = create_compilers();
@@ -31,16 +32,20 @@ export async function build() {
let serviceworker_stats;
if (serviceworker) {
create_serviceworker({
create_serviceworker_manifest({
routes,
client_files: client_stats.toJson().assets.map((chunk: { name: string }) => `/client/${chunk.name}`),
src
client_files: client_stats.toJson().assets.map((chunk: { name: string }) => `/client/${chunk.name}`)
});
serviceworker_stats = await compile(serviceworker);
console.log(clorox.inverse(`\nbuilt service worker`).toString());
console.log(serviceworker_stats.toString({ colors: true }));
}
// minify app/template.html
// TODO compile this to a function? could be quicker than str.replace(...).replace(...).replace(...)
const template = fs.readFileSync(`${locations.app()}/template.html`, 'utf-8');
fs.writeFileSync(`${output}/template.html`, minify_html(template));
}
function compile(compiler: any) {

View File

@@ -9,8 +9,8 @@ import rimraf from 'rimraf';
import format_messages from 'webpack-format-messages';
import prettyMs from 'pretty-ms';
import * as ports from 'port-authority';
import { dest } from '../config';
import { create_compilers, create_app, create_routes, create_serviceworker } from '../core';
import { locations } from '../config';
import { create_compilers, create_main_manifests, create_routes, create_serviceworker_manifest } from '../core';
type Deferred = {
promise?: Promise<any>;
@@ -70,7 +70,7 @@ function create_hot_update_server(port: number, interval = 10000) {
return { send };
}
export async function dev(opts: { port: number }) {
export async function dev(opts: { port: number, open: boolean }) {
process.env.NODE_ENV = 'development';
let port = opts.port || +process.env.PORT;
@@ -84,23 +84,23 @@ export async function dev(opts: { port: number }) {
port = await ports.find(3000);
}
const dir = dest();
const dir = locations.dest();
rimraf.sync(dir);
mkdirp.sync(dir);
const dev_port = await ports.find(10000);
const routes = create_routes();
create_app({ routes, dev_port });
create_main_manifests({ routes, dev_port });
const hot_update_server = create_hot_update_server(dev_port);
watch_files('routes/**/*', ['add', 'unlink'], () => {
watch_files(`${locations.routes()}/**/*`, ['add', 'unlink'], () => {
const routes = create_routes();
create_app({ routes, dev_port });
create_main_manifests({ routes, dev_port });
});
watch_files('app/template.html', ['change'], () => {
watch_files(`${locations.app()}/template.html`, ['change'], () => {
hot_update_server.send({
action: 'reload'
});
@@ -241,6 +241,8 @@ export async function dev(opts: { port: number }) {
}
});
let first = true;
watch(compilers.client, {
name: 'client',
@@ -263,9 +265,15 @@ export async function dev(opts: { port: number }) {
hot_update_server.send({
status: 'completed'
});
if (first) {
first = false;
console.log(`${clorox.bold.cyan(`> Listening on localhost:${port}`)}`);
if (opts.open) child_process.exec(`open http://localhost:${port}`);
}
});
create_serviceworker({
create_serviceworker_manifest({
routes: create_routes(),
client_files
});

View File

@@ -1,14 +1,17 @@
import * as child_process from 'child_process';
import * as path from 'path';
import * as sander from 'sander';
import * as clorox from 'clorox';
import cheerio from 'cheerio';
import URL from 'url-parse';
import fetch from 'node-fetch';
import * as ports from 'port-authority';
import { dest } from '../config';
import prettyBytes from 'pretty-bytes';
import { minify_html } from './utils/minify_html';
import { locations } from '../config';
export async function exporter(export_dir: string) {
const build_dir = dest();
const build_dir = locations.dest();
// Prep output directory
sander.rimrafSync(export_dir);
@@ -40,18 +43,22 @@ export async function exporter(export_dir: string) {
proc.on('message', message => {
if (!message.__sapper__) return;
const url = new URL(message.url, origin);
let file = new URL(message.url, origin).pathname.slice(1);
let { body } = message;
if (saved.has(url.pathname)) return;
saved.add(url.pathname);
if (saved.has(file)) return;
saved.add(file);
if (message.type === 'text/html') {
const file = `${export_dir}/${url.pathname}/index.html`;
sander.writeFileSync(file, message.body);
} else {
const file = `${export_dir}/${url.pathname}`;
sander.writeFileSync(file, message.body);
const is_html = message.type === 'text/html';
if (is_html) {
file = file === '' ? 'index.html' : `${file}/index.html`;
body = minify_html(body);
}
console.log(`${clorox.bold.cyan(file)} ${clorox.gray(`(${prettyBytes(body.length)})`)}`);
sander.writeFileSync(`${export_dir}/${file}`, body);
});
function handle(url: URL) {
@@ -78,7 +85,7 @@ export async function exporter(export_dir: string) {
}
})
.catch((err: Error) => {
console.error(`Error rendering ${url.pathname}: ${err.message}`);
console.log(clorox.red(`> Error rendering ${url.pathname}: ${err.message}`));
});
}

View File

@@ -4,7 +4,7 @@ import * as child_process from 'child_process';
import * as clorox from 'clorox';
import * as ports from 'port-authority';
export async function start(dir: string, opts: { port: number }) {
export async function start(dir: string, opts: { port: number, open: boolean }) {
let port = opts.port || +process.env.PORT;
const resolved = path.resolve(dir);
@@ -32,4 +32,8 @@ export async function start(dir: string, opts: { port: number }) {
SAPPER_DEST: dir
}, process.env)
});
await ports.wait(port);
console.log(`${clorox.bold.cyan(`> Listening on localhost:${port}`)}`);
if (opts.open) child_process.exec(`open http://localhost:${port}`);
}

View File

@@ -0,0 +1,21 @@
import { minify } from 'html-minifier';
export function minify_html(html: string) {
return minify(html, {
collapseBooleanAttributes: true,
collapseWhitespace: true,
conservativeCollapse: true,
decodeEntities: true,
html5: true,
minifyCSS: true,
minifyJS: true,
removeAttributeQuotes: true,
removeComments: true,
removeOptionalTags: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
sortAttributes: true,
sortClassName: true
});
}

View File

@@ -1,5 +1,10 @@
import * as path from 'path';
export const dev = () => process.env.NODE_ENV !== 'production';
export const src = () => path.resolve(process.env.SAPPER_ROUTES || 'routes');
export const dest = () => path.resolve(process.env.SAPPER_DEST || '.sapper');
export const locations = {
base: () => path.resolve(process.env.SAPPER_BASE || ''),
app: () => path.resolve(process.env.SAPPER_BASE || '', process.env.SAPPER_APP || 'app'),
routes: () => path.resolve(process.env.SAPPER_BASE || '', process.env.SAPPER_ROUTES || 'routes'),
dest: () => path.resolve(process.env.SAPPER_BASE || '', process.env.SAPPER_DEST || '.sapper')
};

View File

@@ -1,4 +1,3 @@
export { default as create_app } from './core/create_app';
export { default as create_serviceworker } from './core/create_serviceworker';
export * from './core/create_manifests';
export { default as create_compilers } from './core/create_compilers';
export { default as create_routes } from './core/create_routes';

View File

@@ -1,36 +1,45 @@
import * as fs from 'fs';
import * as path from 'path';
import mkdirp from 'mkdirp';
import * as glob from 'glob';
import create_routes from './create_routes';
import { fudge_mtime, posixify, write } from './utils';
import { dev } from '../config';
import { posixify, write_if_changed } from './utils';
import { dev, locations } from '../config';
import { Route } from '../interfaces';
// in dev mode, we avoid touching the fs unnecessarily
let last_client_manifest: string = null;
let last_server_manifest: string = null;
export default function create_app({ routes, dev_port }: {
export function create_main_manifests({ routes, dev_port }: {
routes: Route[];
dev_port: number;
dev_port?: number;
}) {
mkdirp.sync('app/manifest');
const path_to_routes = path.relative(`${locations.app()}/manifest`, locations.routes());
const client_manifest = generate_client(routes, dev_port);
const server_manifest = generate_server(routes);
const client_manifest = generate_client(routes, path_to_routes, dev_port);
const server_manifest = generate_server(routes, path_to_routes);
if (client_manifest !== last_client_manifest) {
write(`app/manifest/client.js`, client_manifest);
last_client_manifest = client_manifest;
}
if (server_manifest !== last_server_manifest) {
write(`app/manifest/server.js`, server_manifest);
last_server_manifest = server_manifest;
}
write_if_changed(`${locations.app()}/manifest/client.js`, client_manifest);
write_if_changed(`${locations.app()}/manifest/server.js`, server_manifest);
}
function generate_client(routes: Route[], dev_port?: number) {
export function create_serviceworker_manifest({ routes, client_files }: {
routes: Route[];
client_files: string[];
}) {
const assets = glob.sync('**', { cwd: 'assets', nodir: true });
let code = `
// This file is generated by Sapper — do not edit it!
export const timestamp = ${Date.now()};
export const assets = [\n\t${assets.map((x: string) => `"${x}"`).join(',\n\t')}\n];
export const shell = [\n\t${client_files.map((x: string) => `"${x}"`).join(',\n\t')}\n];
export const routes = [\n\t${routes.filter((r: Route) => r.type === 'page' && !/^_[45]xx$/.test(r.id)).map((r: Route) => `{ pattern: ${r.pattern} }`).join(',\n\t')}\n];
`.replace(/^\t\t/gm, '').trim();
write_if_changed(`${locations.app()}/manifest/service-worker.js`, code);
}
function generate_client(routes: Route[], path_to_routes: string, dev_port?: number) {
let code = `
// This file is generated by Sapper — do not edit it!
export const routes = [
@@ -40,7 +49,7 @@ function generate_client(routes: Route[], dev_port?: number) {
return `{ pattern: ${route.pattern}, ignore: true }`;
}
const file = posixify(`../../routes/${route.file}`);
const file = posixify(`${path_to_routes}/${route.file}`);
if (route.id === '_4xx' || route.id === '_5xx') {
return `{ error: '${route.id.slice(1)}', load: () => import(/* webpackChunkName: "${route.id}" */ '${file}') }`;
@@ -72,12 +81,12 @@ function generate_client(routes: Route[], dev_port?: number) {
return code;
}
function generate_server(routes: Route[]) {
function generate_server(routes: Route[], path_to_routes: string) {
let code = `
// This file is generated by Sapper — do not edit it!
${routes
.map(route => {
const file = posixify(`../../routes/${route.file}`);
const file = posixify(`${path_to_routes}/${route.file}`);
return route.type === 'page'
? `import ${route.id} from '${file}';`
: `import * as ${route.id} from '${file}';`;

View File

@@ -1,9 +1,9 @@
import * as path from 'path';
import glob from 'glob';
import { src } from '../config';
import { locations } from '../config';
import { Route } from '../interfaces';
export default function create_routes({ files } = { files: glob.sync('**/*.*', { cwd: src(), nodir: true }) }) {
export default function create_routes({ files } = { files: glob.sync('**/*.*', { cwd: locations.routes(), nodir: true }) }) {
const routes: Route[] = files
.map((file: string) => {
if (/(^|\/|\\)_/.test(file)) return;

View File

@@ -1,26 +0,0 @@
import * as fs from 'fs';
import * as path from 'path';
import glob from 'glob';
import create_routes from './create_routes';
import { fudge_mtime, posixify, write } from './utils';
import { Route } from '../interfaces';
export default function create_serviceworker({ routes, client_files }: {
routes: Route[];
client_files: string[];
}) {
const assets = glob.sync('**', { cwd: 'assets', nodir: true });
let code = `
// This file is generated by Sapper — do not edit it!
export const timestamp = ${Date.now()};
export const assets = [\n\t${assets.map((x: string) => `"${x}"`).join(',\n\t')}\n];
export const shell = [\n\t${client_files.map((x: string) => `"${x}"`).join(',\n\t')}\n];
export const routes = [\n\t${routes.filter((r: Route) => r.type === 'page' && !/^_[45]xx$/.test(r.id)).map((r: Route) => `{ pattern: ${r.pattern} }`).join(',\n\t')}\n];
`.replace(/^\t\t/gm, '').trim();
write('app/manifest/service-worker.js', code);
}

View File

@@ -1,8 +1,13 @@
import * as fs from 'fs';
import * as sander from 'sander';
export function write(file: string, code: string) {
fs.writeFileSync(file, code);
fudge_mtime(file);
const previous_contents = new Map();
export function write_if_changed(file: string, code: string) {
if (code !== previous_contents.get(file)) {
previous_contents.set(file, code);
sander.writeFileSync(file, code);
fudge_mtime(file);
}
}
export function posixify(file: string) {
@@ -11,8 +16,8 @@ export function posixify(file: string) {
export function fudge_mtime(file: string) {
// need to fudge the mtime so that webpack doesn't go doolally
const { atime, mtime } = fs.statSync(file);
fs.utimesSync(
const { atime, mtime } = sander.statSync(file);
sander.utimesSync(
file,
new Date(atime.getTime() - 999999),
new Date(mtime.getTime() - 999999)

View File

@@ -5,8 +5,8 @@ import mkdirp from 'mkdirp';
import rimraf from 'rimraf';
import devalue from 'devalue';
import { lookup } from './middleware/mime';
import { create_routes, templates, create_compilers } from './core/index';
import { dest, dev } from './config';
import { create_routes, create_compilers } from './core';
import { locations, dev } from './config';
import { Route, Template } from './interfaces';
import sourceMapSupport from 'source-map-support';
@@ -40,7 +40,7 @@ interface Req extends ClientRequest {
export default function middleware({ routes }: {
routes: RouteObject[]
}) {
const output = dest();
const output = locations.dest();
const client_info = JSON.parse(fs.readFileSync(path.join(output, 'client_info.json'), 'utf-8'));
@@ -80,7 +80,7 @@ function serve({ prefix, pathname, cache_control }: {
? (req: Req) => req.pathname === pathname
: (req: Req) => req.pathname.startsWith(prefix);
const output = dest();
const output = locations.dest();
const cache: Map<string, Buffer> = new Map();
@@ -112,8 +112,8 @@ const resolved = Promise.resolve();
function get_route_handler(chunks: Record<string, string>, routes: RouteObject[]) {
const template = dev()
? () => fs.readFileSync('app/template.html', 'utf-8')
: (str => () => str)(fs.readFileSync('app/template.html', 'utf-8'));
? () => fs.readFileSync(`${locations.app()}/template.html`, 'utf-8')
: (str => () => str)(fs.readFileSync(`${locations.dest()}/template.html`, 'utf-8'));
function handle_route(route: RouteObject, req: Req, res: ServerResponse) {
req.params = route.params(route.pattern.exec(req.pathname));

View File

@@ -1,4 +1,4 @@
import { dest, dev } from './config';
import { locations, dev } from './config';
export default {
dev: dev(),
@@ -6,13 +6,13 @@ export default {
client: {
entry: () => {
return {
main: './app/client'
main: `${locations.app()}/client`
};
},
output: () => {
return {
path: `${dest()}/client`,
path: `${locations.dest()}/client`,
filename: '[hash]/[name].js',
chunkFilename: '[hash]/[name].[id].js',
publicPath: '/client/'
@@ -23,13 +23,13 @@ export default {
server: {
entry: () => {
return {
server: './app/server'
server: `${locations.app()}/server`
};
},
output: () => {
return {
path: dest(),
path: locations.dest(),
filename: '[name].js',
chunkFilename: '[hash]/[name].[id].js',
libraryTarget: 'commonjs2'
@@ -40,13 +40,13 @@ export default {
serviceworker: {
entry: () => {
return {
'service-worker': './app/service-worker'
'service-worker': `${locations.app()}/service-worker`
};
},
output: () => {
return {
path: dest(),
path: locations.dest(),
filename: '[name].js',
chunkFilename: '[name].[id].[hash].js'
}

View File

@@ -2,7 +2,7 @@ import fs from 'fs';
import polka from 'polka';
import compression from 'compression';
import serve from 'serve-static';
import sapper from '../../../middleware';
import sapper from '../../../dist/middleware.ts.js';
import { routes } from './manifest/server.js';
let pending;