Skip to content

Commit

Permalink
add hmr for build
Browse files Browse the repository at this point in the history
  • Loading branch information
MoonBall committed Sep 11, 2020
1 parent e5dfccc commit d8042ca
Show file tree
Hide file tree
Showing 6 changed files with 29 additions and 8 deletions.
18 changes: 17 additions & 1 deletion snowpack/src/commands/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,18 @@ import {
relativeURL,
removeLeadingSlash,
replaceExt,
HMR_CLIENT_CODE,
} from '../util';
import {getInstallTargets, run as installRunner} from './install';
import { EsmHmrEngine } from '../hmr-server-engine';

const CONCURRENT_WORKERS = require('os').cpus().length;

let hmrEngine: EsmHmrEngine | null = null;
function getIsHmrEnabled(config: SnowpackConfig) {
return config.buildOptions.watch && !!config.devOptions.hmr;
}

async function installOptimizedDependencies(
scannedFiles: SnowpackSourceFile[],
installDest: string,
Expand Down Expand Up @@ -139,7 +146,7 @@ class FileBuilder {
case '.html': {
code = wrapHtmlResponse({
code,
hmr: false,
hmr: getIsHmrEnabled(this.config),
isDev: false,
config: this.config,
mode: 'production',
Expand Down Expand Up @@ -289,6 +296,11 @@ export async function command(commandOptions: CommandOptions) {

// Write the `import.meta.env` contents file to disk
await fs.writeFile(path.join(internalFilesBuildLoc, 'env.js'), generateEnvModule('production'));
if (getIsHmrEnabled(config)) {
await fs.writeFile(path.resolve(internalFilesBuildLoc, 'hmr.js'), HMR_CLIENT_CODE);
hmrEngine = new EsmHmrEngine();
logger.info(`[ESM-HMR] web socket's url is ${colors.cyan(`${hmrEngine.wsUrl}`)}`);
}

logger.info(colors.yellow('! building source…'));
const buildStart = performance.now();
Expand Down Expand Up @@ -449,6 +461,10 @@ export async function command(commandOptions: CommandOptions) {
await changedPipelineFile.writeProxyToDisk(builtFile);
}
}

if (hmrEngine) {
hmrEngine.broadcastMessage({type: 'reload'});
}
}
const watcher = chokidar.watch(
mountedDirectories.map(([dirDisk]) => dirDisk),
Expand Down
9 changes: 5 additions & 4 deletions snowpack/src/commands/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import isCompressible from 'compressible';
import merge from 'deepmerge';
import etag from 'etag';
import {EventEmitter} from 'events';
import {createReadStream, existsSync, promises as fs, readFileSync, statSync} from 'fs';
import {createReadStream, existsSync, promises as fs, statSync} from 'fs';
import http from 'http';
import HttpProxy from 'http-proxy';
import http2 from 'http2';
Expand Down Expand Up @@ -76,10 +76,10 @@ import {
replaceExt,
resolveDependencyManifest,
updateLockfileHash,
HMR_CLIENT_CODE,
} from '../util';
import {command as installCommand} from './install';
import {getPort, paint, paintEvent} from './paint';
const HMR_DEV_CODE = readFileSync(path.join(__dirname, '../assets/hmr.js'));

const DEFAULT_PROXY_ERROR_HANDLER = (
err: Error,
Expand Down Expand Up @@ -203,7 +203,8 @@ function getUrlFromFile(

export async function command(commandOptions: CommandOptions) {
const {cwd, config} = commandOptions;
const {port: defaultPort, hostname, open, hmr: isHmr} = config.devOptions;
const {port: defaultPort, hostname, open } = config.devOptions;
const isHmr = typeof config.devOptions.hmr !== 'undefined' ? config.devOptions.hmr : true;

// Start the startup timer!
let serverStart = performance.now();
Expand Down Expand Up @@ -365,7 +366,7 @@ export async function command(commandOptions: CommandOptions) {
});

if (reqPath === getMetaUrlPath('/hmr.js', config)) {
sendFile(req, res, HMR_DEV_CODE, reqPath, '.js');
sendFile(req, res, HMR_CLIENT_CODE, reqPath, '.js');
return;
}
if (reqPath === getMetaUrlPath('/env.js', config)) {
Expand Down
1 change: 0 additions & 1 deletion snowpack/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@ const DEFAULT_CONFIG: Partial<SnowpackConfig> = {
open: 'default',
out: 'build',
fallback: 'index.html',
hmr: true,
},
buildOptions: {
baseUrl: '/',
Expand Down
5 changes: 4 additions & 1 deletion snowpack/src/hmr-server-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,17 @@ interface Dependency {
needsReplacementCount: number;
}

const DEFAULT_PORT = 12321;

export class EsmHmrEngine {
clients: Set<WebSocket> = new Set();
dependencyTree = new Map<string, Dependency>();
wsUrl = `ws://localhost:${DEFAULT_PORT}`;

constructor(options: {server?: http.Server | http2.Http2Server} = {}) {
const wss = options.server
? new WebSocket.Server({noServer: true})
: new WebSocket.Server({port: 12321});
: new WebSocket.Server({port: DEFAULT_PORT});
if (options.server) {
options.server.on('upgrade', (req, socket, head) => {
// Only handle upgrades to ESM-HMR requests, ignore others.
Expand Down
2 changes: 1 addition & 1 deletion snowpack/src/types/snowpack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ export interface SnowpackConfig {
out: string;
fallback: string;
open: string;
hmr: boolean;
hmr?: boolean;
};
installOptions: {
dest: string;
Expand Down
2 changes: 2 additions & 0 deletions snowpack/src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -409,3 +409,5 @@ export function removeLeadingSlash(path: string) {
export function removeTrailingSlash(path: string) {
return path.replace(/[/\\]+$/, '');
}

export const HMR_CLIENT_CODE = fs.readFileSync(path.join(__dirname, '../assets/hmr.js'), 'utf-8');

0 comments on commit d8042ca

Please sign in to comment.