Skip to content

Commit

Permalink
More similar to SvelteKit:
Browse files Browse the repository at this point in the history
	ESM
	+ ssr: global fetch,Request,Response,Headers
	sveltejs#1791
  • Loading branch information
btakita committed Jul 20, 2021
1 parent a4b26c0 commit e0e783a
Show file tree
Hide file tree
Showing 18 changed files with 177 additions and 93 deletions.
3 changes: 2 additions & 1 deletion config/rollup.js
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
module.exports = require('../dist/rollup.js');
import { default as rollup } from '../dist/rollup.js';
export default rollup;
3 changes: 2 additions & 1 deletion config/webpack.js
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
module.exports = require('../dist/webpack.js');
export { default as webpack } from '../dist/webpack.js';
export default webpack;
74 changes: 38 additions & 36 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
"version": "0.29.1",
"description": "The next small thing in web development, powered by Svelte",
"bin": {
"sapper": "./sapper"
"sapper": "./dist/cli.js"
},
"type": "module",
"files": [
"*.js",
"webpack",
Expand All @@ -20,58 +21,59 @@
},
"dependencies": {
"html-minifier": "^4.0.0",
"http-link-header": "^1.0.2",
"http-link-header": "^1.0.3",
"shimport": "^2.0.5",
"source-map": "^0.6.1",
"sourcemap-codec": "^1.4.6",
"sourcemap-codec": "^1.4.8",
"string-hash": "^1.1.3"
},
"devDependencies": {
"@rollup/plugin-commonjs": "^13.0.0",
"@rollup/plugin-commonjs": "^13.0.2",
"@rollup/plugin-json": "^4.1.0",
"@rollup/plugin-node-resolve": "^8.0.1",
"@rollup/plugin-replace": "^2.3.3",
"@rollup/plugin-node-resolve": "^8.4.0",
"@rollup/plugin-replace": "^2.4.2",
"@sveltejs/eslint-config": "github:sveltejs/eslint-config#v5.4.0",
"@types/cookie": "^0.4.0",
"@types/mocha": "^8.0.0",
"@types/node": "^10.0.0",
"@types/node-fetch": "^2.5.7",
"@types/puppeteer": "^3.0.1",
"@typescript-eslint/eslint-plugin": "^4.3.0",
"@typescript-eslint/parser": "^4.3.0",
"cheap-watch": "^1.0.2",
"@types/cookie": "^0.4.1",
"@types/mocha": "^8.2.3",
"@types/node": "^10.17.60",
"@types/node-fetch": "^2.5.11",
"@types/puppeteer": "^3.0.6",
"@typescript-eslint/eslint-plugin": "^4.28.4",
"@typescript-eslint/parser": "^4.28.4",
"cheap-watch": "workspace:^1.0.3",
"cookie": "^0.4.1",
"cross-env": "^7.0.2",
"devalue": "^2.0.0",
"eslint": "^7.10.0",
"eslint-import-resolver-typescript": "^2.2.0",
"eslint-plugin-import": "^2.22.1",
"cross-env": "^7.0.3",
"devalue": "^2.0.1",
"eslint": "^7.31.0",
"eslint-import-resolver-typescript": "^2.4.0",
"eslint-plugin-import": "^2.23.4",
"eslint-plugin-svelte3": "^2.7.3",
"kleur": "^4.0.0",
"mime": "^2.4.4",
"mocha": "^8.0.0",
"node-fetch": "^2.6.0",
"import-meta-resolve": "^1.1.1",
"kleur": "^4.1.4",
"mime": "^2.5.2",
"mocha": "^8.4.0",
"node-fetch": "^2.6.1",
"npm-run-all": "^4.1.5",
"polka": "^0.5.2",
"port-authority": "^1.0.5",
"pretty-bytes": "^5.3.0",
"puppeteer": "^5.0.0",
"port-authority": "^1.1.2",
"pretty-bytes": "^5.6.0",
"puppeteer": "^5.5.0",
"require-relative": "^0.8.7",
"rimraf": "^3.0.2",
"rollup": "^2.29.0",
"rollup": "^2.53.2",
"rollup-dependency-tree": "0.0.14",
"rollup-plugin-css-chunks": "^2.0.3",
"rollup-plugin-svelte": "^5.1.0",
"rollup-plugin-typescript2": "^0.27.1",
"sade": "^1.6.1",
"sirv": "^1.0.0",
"svelte": "^3.24.0",
"rollup-plugin-svelte": "^5.2.3",
"rollup-plugin-typescript2": "^0.27.3",
"sade": "^1.7.4",
"sirv": "^1.0.12",
"svelte": "^3.38.3",
"svelte-loader": "^2.13.6",
"ts-node": "^8.10.2",
"tslib": "^2.0.0",
"typescript": "^4.0.3",
"webpack": "^4.38.0",
"webpack-format-messages": "^2.0.5",
"tslib": "^2.3.0",
"typescript": "^4.3.5",
"webpack": "^4.46.0",
"webpack-format-messages": "^2.0.6",
"webpack-modules": "^1.0.0"
},
"peerDependencies": {
Expand Down
5 changes: 3 additions & 2 deletions rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,11 @@ export default [
],
output: {
dir: 'dist',
format: 'cjs',
format: 'es',
interop: false,
sourcemap: true,
chunkFileNames: '[name].js'
chunkFileNames: '[name].js',
exports: 'auto'
},
external,
plugins: [
Expand Down
3 changes: 2 additions & 1 deletion runtime/src/server/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export { default as middleware } from './middleware/index';
import './install-fetch.js';
export { default as middleware } from './middleware/index.js';
24 changes: 24 additions & 0 deletions runtime/src/server/install-fetch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import fetch, { Response, Request, Headers } from 'node-fetch';

// exported for dev, prerender, and preview
export function __fetch_polyfill() {
Object.defineProperties(globalThis, {
fetch: {
enumerable: true,
value: fetch
},
Response: {
enumerable: true,
value: Response
},
Request: {
enumerable: true,
value: Request
},
Headers: {
enumerable: true,
value: Headers
}
});
}
__fetch_polyfill();
2 changes: 0 additions & 2 deletions sapper

This file was deleted.

14 changes: 6 additions & 8 deletions src/api/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import * as http from 'http';
import * as child_process from 'child_process';
import * as ports from 'port-authority';
import { EventEmitter } from 'events';
import CheapWatch from 'cheap-watch';
import { create_manifest_data, create_app, create_compilers, create_serviceworker_manifest } from '../core';
import { Compiler, Compilers } from '../core/create_compilers';
import { CompileResult } from '../core/create_compilers/interfaces';
Expand Down Expand Up @@ -493,17 +494,14 @@ function watch_dir(
let watch: any;
let closed = false;

import('cheap-watch').then(({ default: CheapWatch }) => {
if (closed) return;
if (closed) return;
watch = new CheapWatch({ dir, filter, debounce: 50 }) as CheapWatch;

watch = new CheapWatch({ dir, filter, debounce: 50 });
watch.on('+', callback);

watch.on('+', callback);
watch.on('-', callback);

watch.on('-', callback);

watch.init();
});
watch.init();

return {
close: () => {
Expand Down
5 changes: 4 additions & 1 deletion src/api/utils/copy_runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@ const runtime = [
'internal/error.svelte'
].map(file => ({
file,
source: fs.readFileSync(path.join(__dirname, `../runtime/${file}`), 'utf-8')
source: fs.readFileSync(
path.join(path.dirname(new URL(import.meta.url).pathname), `../runtime/${file}`),
'utf-8'
)
}));

export function copy_runtime(output: string) {
Expand Down
10 changes: 7 additions & 3 deletions src/api/utils/copy_shimport.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import * as fs from 'fs';
import { promisify } from 'util';
import { version as shimport_version } from 'shimport/package.json';
import { resolve } from 'import-meta-resolve';

export function copy_shimport(dest: string) {
fs.writeFileSync(
export async function copy_shimport(dest: string) {
await promisify(fs.writeFile)(
`${dest}/client/shimport@${shimport_version}.js`,
fs.readFileSync(require.resolve('shimport/index.js'))
fs.readFileSync(
new URL(await resolve('shimport/index.js', import.meta.url)).pathname
)
);
}
18 changes: 16 additions & 2 deletions src/config/rollup.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { dev, src, dest } from './env';
import { accessSync, constants } from 'fs';
import { InputOption, OutputOptions } from 'rollup';
import { dev, src, dest } from './env';
import path from 'path';

const sourcemap = dev ? 'inline' : false;

Expand Down Expand Up @@ -35,7 +37,7 @@ export default {
output: (): OutputOptions => {
return {
dir: `${dest}/server`,
format: 'cjs',
format: get_server_format(),
sourcemap
};
}
Expand All @@ -55,3 +57,15 @@ export default {
}
}
};
function get_server_format() {
const cwd = '.'
try {
const input = path.resolve(cwd, 'rollup.config.mjs')
accessSync(input, constants.F_OK | constants.R_OK)
return 'es'
} catch (_e) {
const input = path.resolve(cwd, 'rollup.config.js')
accessSync(input, constants.F_OK | constants.R_OK)
return 'cjs'
}
}
2 changes: 1 addition & 1 deletion src/core/create_app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ function generate_client_manifest(
export const routes = ${routes};
${dev ? `if (typeof window !== 'undefined') {
import(${stringify(posixify(path.resolve(__dirname, '../sapper-dev-client.js')))}).then(client => {
import(${stringify(posixify(path.resolve(path.dirname(new URL(import.meta.url).pathname), '../sapper-dev-client.js')))}).then(client => {
client.connect(${dev_port});
});
}` : ''}
Expand Down
66 changes: 37 additions & 29 deletions src/core/create_compilers/RollupCompiler.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import * as path from 'path';
import { access, constants } from 'fs/promise';
import color from 'kleur';
import relative from 'require-relative';
import { dependenciesForTree, DependencyTreeOptions } from 'rollup-dependency-tree';
Expand All @@ -15,14 +14,15 @@ import {
} from 'rollup';
import { CompileResult } from './interfaces';
import RollupResult from './RollupResult';
import { get_config_extname } from './config_extname.js';

const stderr = console.error.bind(console);
const INJECT_STYLES_NAME = 'inject_styles';
const INJECT_STYLES_ID = 'inject_styles.js';

let rollup: any;

function printTimings(timings: {[event: string]: [number, number, number]}) {
function printTimings(timings:{ [event: string]: [number, number, number] }) {
for (const [key, info] of Object.entries(timings)) {
console.info(`${key} took ${info[0].toFixed(0)}ms`);
}
Expand Down Expand Up @@ -118,6 +118,7 @@ export default class RollupCompiler {
css_files: Record<string, string>;
dependencies: Record<string, string[]>;
routes: string;
esm: boolean;

constructor(config: any, routes: string) {
this._ = this.get_config(config);
Expand Down Expand Up @@ -354,7 +355,7 @@ export default class RollupCompiler {
this.warnings = [];
this.errors = [];
this._oninvalid(id);
});
})

watcher.on('event', (event: any) => {
switch (event.code) {
Expand Down Expand Up @@ -396,23 +397,26 @@ export default class RollupCompiler {
default:
console.log(`Unexpected event ${event.code}`);
}
});
})
}

static async load_config(cwd: string) {
if (!rollup) rollup = relative('rollup', cwd);

let input: string;
try {
input = path.resolve(cwd, 'rollup.config.mjs');
await access(input, constants.F_OK | constants.R_OK);
} catch (_e) {
input = path.resolve(cwd, 'rollup.config.js');
await access(input, constants.F_OK | constants.R_OK);
}

let input: string, format: string, esm: boolean;
const config_extname = await get_config_extname(cwd);
if (config_extname === '.cjs') {
input = path.resolve(cwd, 'rollup.config.js');
format = 'cjs';
esm = false;
} else if (config_extname === '.mjs') {
input = path.resolve(cwd, 'rollup.config.mjs');
format = 'es';
esm = true;
}
const bundle = await rollup.rollup({
input,
format,
inlineDynamicImports: true,
external: (id: string) => {
return (id[0] !== '.' && !path.isAbsolute(id)) || id.slice(-5, id.length) === '.json';
Expand All @@ -423,27 +427,31 @@ export default class RollupCompiler {
output: [{ code }]
} = await bundle.generate({
exports: 'named',
format: 'cjs'
format
});

// temporarily override require
const defaultLoader = require.extensions['.js'];
require.extensions['.js'] = (module: any, filename: string) => {
if (filename === input) {
module._compile(code, filename);
} else {
defaultLoader(module, filename);
if (!esm) {
// temporarily override require
const defaultLoader = require.extensions['.js'];
require.extensions['.js'] = (module: any, filename: string) => {
if (filename === input) {
module._compile(code, filename);
} else {
defaultLoader(module, filename);
}
}
};

const config: any = require(input).default; // eslint-disable-line
delete require.cache[input];
}

return config;
if (esm) {
return (await import(input)).default;
} else {
const config = require(input).default;
delete require.cache[input];
return config;
}
}
}


// copied from https://github.com/rollup/rollup/blob/master/cli/logging.ts
// and updated so that it will compile here

Expand All @@ -452,8 +460,8 @@ export function handleError(err: RollupError, recover = false) {
if (err.name) description = `${err.name}: ${description}`;
const message =
(err.plugin
? `(plugin ${(err).plugin}) ${description}`
: description) || err;
? `(plugin ${(err).plugin}) ${description}`
: description) || err;

stderr(color.bold().red(`[!] ${color.bold(message.toString())}`));

Expand Down

0 comments on commit e0e783a

Please sign in to comment.