Skip to content

Commit e905d33

Browse files
committed
chore(vite): make devserver work
- support vite base - build qrls on demand
1 parent 74110ee commit e905d33

File tree

3 files changed

+46
-93
lines changed

3 files changed

+46
-93
lines changed

packages/qwik/src/optimizer/src/plugins/plugin.ts

Lines changed: 15 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -296,7 +296,6 @@ export function createPlugin(optimizerOptions: OptimizerOptions = {}) {
296296
} else {
297297
opts.lint = updatedOpts.buildMode === 'development';
298298
}
299-
console.dir(opts);
300299
return { ...opts };
301300
};
302301

@@ -326,7 +325,6 @@ export function createPlugin(optimizerOptions: OptimizerOptions = {}) {
326325
};
327326

328327
let didAddQwikEntries = false;
329-
const jsPacketIdSource = new Map<string, string>();
330328
const buildStart = async (ctx: Rollup.PluginContext) => {
331329
debug(`buildStart()`, opts.buildMode, opts.scope, opts.target);
332330
const optimizer = getOptimizer();
@@ -388,36 +386,20 @@ export function createPlugin(optimizerOptions: OptimizerOptions = {}) {
388386
moduleSideEffects: false,
389387
};
390388
}
391-
let firstInput: string;
392-
if (Array.isArray(opts.input)) {
393-
firstInput = opts.input[0];
394-
} else {
395-
firstInput = Object.values(opts.input)[0];
396-
}
389+
390+
const firstInput = Object.values(opts.input)[0];
397391
return {
398392
id: normalizePath(getPath().resolve(firstInput, QWIK_CLIENT_MANIFEST_ID)),
399393
moduleSideEffects: false,
400394
};
401395
}
402396

403397
const path = getPath();
404-
const isSSR = resolveOpts?.ssr ?? opts.target === 'ssr';
398+
const isSSR = !!resolveOpts?.ssr;
405399

406400
if (importer) {
407-
if (!isSSR && importer.endsWith('.html')) {
408-
const match = id.match(/.js?qrl=(.*)$/);
409-
console.log('dev server asking for jsPacket', path.isAbsolute(id), match);
410-
if (match) {
411-
const jsPacketId = match[1];
412-
const sourceId = jsPacketIdSource.get(jsPacketId);
413-
if (sourceId) {
414-
await ctx.load({ id: sourceId });
415-
// Now all jsPackets exist in the cache
416-
}
417-
}
418-
}
419-
// Only process relative links
420-
if (!id.startsWith('.') && (!path.isAbsolute(id) || !importer.endsWith('.html'))) {
401+
// Only process real files
402+
if (!(id.startsWith('.') || path.isAbsolute(id))) {
421403
return;
422404
}
423405
const parsedId = parseId(id);
@@ -462,6 +444,7 @@ export function createPlugin(optimizerOptions: OptimizerOptions = {}) {
462444
}
463445
}
464446
}
447+
// we don't know what this is
465448
return null;
466449
};
467450
const load = async (
@@ -519,7 +502,7 @@ export function createPlugin(optimizerOptions: OptimizerOptions = {}) {
519502
return generateQwikEntries(transformedOutputs);
520503
}
521504

522-
const isSSR = loadOpts?.ssr ?? opts.target === 'ssr';
505+
const isSSR = !!loadOpts?.ssr;
523506
if (opts.resolveQwikBuild && id.endsWith(QWIK_BUILD_ID)) {
524507
debug(`load()`, QWIK_BUILD_ID, opts.buildMode);
525508
return {
@@ -543,31 +526,22 @@ export function createPlugin(optimizerOptions: OptimizerOptions = {}) {
543526

544527
if (transformedModule) {
545528
debug(`load()`, 'Found', id);
529+
let { code } = transformedModule[0];
530+
const { map, hook } = transformedModule[0];
546531

547-
let code = transformedModule[0].code;
548-
let firstInput: string;
549-
if (Array.isArray(opts.input)) {
550-
firstInput = opts.input[0];
551-
} else {
552-
firstInput = Object.values(opts.input)[0];
553-
}
554532
if (opts.target === 'ssr') {
533+
const firstInput = Object.values(opts.input)[0];
555534
// doing this because vite will not use resolveId() when "noExternal" is false
556535
// so we need to turn the @qwik-client-manifest import into a relative import
557536
code = code.replace(
558537
/@qwik-client-manifest/g,
559538
normalizePath(path.resolve(firstInput, QWIK_CLIENT_MANIFEST_ID))
560539
);
561540
}
562-
return {
563-
code,
564-
map: transformedModule[0].map,
565-
meta: {
566-
hook: transformedModule[0].hook,
567-
},
568-
};
541+
return { code, map, meta: { hook } };
569542
}
570543

544+
debug('load()', 'Not found', id);
571545
return null;
572546
};
573547

@@ -580,7 +554,7 @@ export function createPlugin(optimizerOptions: OptimizerOptions = {}) {
580554
if (id.startsWith('\0') || id.startsWith('/@fs/')) {
581555
return;
582556
}
583-
const isSSR = transformOpts.ssr ?? opts.target === 'ssr';
557+
const isSSR = transformOpts.ssr;
584558
const currentOutputs = isSSR ? ssrTransformedOutputs : transformedOutputs;
585559
if (currentOutputs.has(id)) {
586560
return;
@@ -644,7 +618,7 @@ export function createPlugin(optimizerOptions: OptimizerOptions = {}) {
644618

645619
const newOutput = optimizer.transformModulesSync(transformOpts);
646620
// uncomment to show transform results
647-
debug({ isSSR, strip }, transformOpts, newOutput);
621+
// debug({ isSSR, strip }, transformOpts, newOutput);
648622
diagnosticsCallback(newOutput.diagnostics, optimizer, srcDir);
649623

650624
if (isSSR) {
@@ -664,47 +638,6 @@ export function createPlugin(optimizerOptions: OptimizerOptions = {}) {
664638
ctx.addWatchFile(key);
665639
}
666640
}
667-
if (isSSR && strip) {
668-
// We also need a client build with the server code stripped
669-
// so that we know all the possible jsPackets that are used
670-
const clientTransformOpts: TransformModulesOptions = {
671-
input: [{ code, path: filePath }],
672-
entryStrategy: opts.entryStrategy,
673-
minify: 'simplify',
674-
sourceMaps: opts.sourcemap || 'development' === opts.buildMode,
675-
transpileTs: true,
676-
transpileJsx: true,
677-
explicitExtensions: true,
678-
preserveFilenames: true,
679-
srcDir: srcDir,
680-
rootDir: opts.rootDir,
681-
mode: mode,
682-
scope: opts.scope ? opts.scope : void 0,
683-
stripCtxName: SERVER_STRIP_CTX_NAME,
684-
stripExports: SERVER_STRIP_EXPORTS,
685-
isServer: false,
686-
};
687-
const clientNewOutput = optimizer.transformModulesSync(clientTransformOpts);
688-
debug('client build', transformOpts, newOutput);
689-
690-
diagnosticsCallback(clientNewOutput.diagnostics, optimizer, srcDir);
691-
692-
results.set(normalizedID, clientNewOutput);
693-
for (const mod of clientNewOutput.modules) {
694-
if (isAdditionalFile(mod)) {
695-
const key = normalizePath(path.join(srcDir, mod.path));
696-
transformedOutputs.set(key, [mod, id]);
697-
// these are in ssr context and should be in client context
698-
// deps.add(key);
699-
// ctx.addWatchFile(key);
700-
if (mod.hook) {
701-
currentOutputs.set(mod.hook.name, [mod, id]);
702-
jsPacketIdSource.set(mod.hook.name, id);
703-
console.log('hook', mod.hook.name.toLowerCase(), id);
704-
}
705-
}
706-
}
707-
}
708641

709642
// Force loading generated submodules into Rollup cache so later
710643
// unchanged imports are not missing in our internal transform cache
@@ -779,7 +712,7 @@ export function createPlugin(optimizerOptions: OptimizerOptions = {}) {
779712
};
780713

781714
const debug = (...str: any[]) => {
782-
if (true || opts.debug) {
715+
if (opts.debug) {
783716
// eslint-disable-next-line no-console
784717
console.debug(`[QWIK PLUGIN: ${id}]`, ...str);
785718
}

packages/qwik/src/optimizer/src/plugins/vite-server.ts

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ function getOrigin(req: IncomingMessage) {
2828
}
2929

3030
export async function configureDevServer(
31+
base: string,
3132
server: ViteDevServer,
3233
opts: NormalizedQwikPluginOptions,
3334
sys: OptimizerSystem,
@@ -54,7 +55,7 @@ export async function configureDevServer(
5455
}
5556

5657
// qwik middleware injected BEFORE vite internal middlewares
57-
server.middlewares.use(async (req: any, res: any, next: any) => {
58+
server.middlewares.use(async (req, res, next) => {
5859
try {
5960
const { ORIGIN } = process.env;
6061
const domain = ORIGIN ?? getOrigin(req);
@@ -152,16 +153,16 @@ export async function configureDevServer(
152153
if (symbolName === SYNC_QRL) {
153154
return [symbolName, ''];
154155
}
155-
const defaultChunk = [
156-
symbolName,
157-
`${import.meta.env.BASE_URL}${parent ? `${srcBase}/${parent}?qrl=` : '@qrl/'}${symbolName.toLowerCase()}`,
158-
] as const;
159-
if (mapper) {
160-
const hash = getSymbolHash(symbolName);
161-
return mapper[hash] ?? defaultChunk;
162-
} else {
163-
return defaultChunk;
156+
const chunk = mapper && mapper[getSymbolHash(symbolName)];
157+
if (chunk) {
158+
return chunk;
164159
}
160+
if (!parent) {
161+
console.error('unknown qrl requested without parent:', symbolName);
162+
return [symbolName, `${base}${symbolName.toLowerCase()}.js`];
163+
}
164+
const packetFile = `${path.dirname(parent)}/${symbolName.toLowerCase()}.js?_qrl_parent=/${srcBase}/${parent}`;
165+
return [symbolName, `${base}${srcBase}/${packetFile}`];
165166
},
166167
prefetchStrategy: null,
167168
serverData,
@@ -206,6 +207,17 @@ export async function configureDevServer(
206207
next();
207208
}
208209
} else {
210+
// We didn't ssr, but maybe a qrl was requested
211+
const parent = url.searchParams.get('_qrl_parent');
212+
if (parent && url.pathname.endsWith('.js')) {
213+
// load the parent so it populates the qrl cache
214+
await server.transformRequest(parent);
215+
const result = await server.transformRequest(url.pathname);
216+
if (result) {
217+
res.write(result.code);
218+
res.end();
219+
}
220+
}
209221
next();
210222
}
211223
} catch (e: any) {

packages/qwik/src/optimizer/src/plugins/vite.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -649,7 +649,15 @@ export function qwikVite(qwikViteOpts: QwikVitePluginOptions = {}): any {
649649
const opts = qwikPlugin.getOptions();
650650
const sys = qwikPlugin.getSys();
651651
const path = qwikPlugin.getPath();
652-
await configureDevServer(server, opts, sys, path, isClientDevOnly, clientDevInput);
652+
await configureDevServer(
653+
basePathname,
654+
server,
655+
opts,
656+
sys,
657+
path,
658+
isClientDevOnly,
659+
clientDevInput
660+
);
653661
};
654662
const isNEW = (globalThis as any).__qwikCityNew === true;
655663
if (isNEW) {

0 commit comments

Comments
 (0)