Skip to content

Commit c0b44f9

Browse files
committed
fix(pfe-tools): redirect .js to .ts only on 404
The previous approach (serve hook) broke esbuild compilation because returning from serve() prevents other plugins from running. Instead, keep the koa middleware but call next() first, then redirect to .ts only when the .js file doesn't exist (404). This is backwards compatible: when compiled .js exists, it serves normally. Assisted-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent 4b95cc3 commit c0b44f9

1 file changed

Lines changed: 12 additions & 16 deletions

File tree

tools/pfe-tools/dev-server/config.ts

Lines changed: 12 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import type { Plugin, Context } from '@web/dev-server-core';
1+
import type { Plugin, Context, Middleware } from '@web/dev-server-core';
22
import type { DevServerConfig } from '@web/dev-server';
33

44
import { readdir, stat } from 'node:fs/promises';
@@ -85,19 +85,17 @@ async function cacheBusterMiddleware(ctx: Context, next: () => Promise<any>) {
8585
}
8686
}
8787

88-
function tsRedirectPlugin(
88+
function liveReloadTsChangesMiddleware(
8989
config: ReturnType<typeof normalizeOptions>,
90-
): Plugin {
91-
const TYPESCRIPT_SOURCES_RE = new RegExp(`(${config.elementsDir}|pfe-core)/.*\\.js$`);
92-
return {
93-
name: 'pfe-ts-redirect',
94-
serve(context) {
95-
if (!context.path.includes('node_modules')
96-
&& TYPESCRIPT_SOURCES_RE.test(context.path)) {
97-
// Rewrite .js to .ts so esbuild plugin can compile it
98-
context.path = context.path.replace(/\.js$/, '.ts');
99-
}
100-
},
90+
): Middleware {
91+
const TYPESCRIPT_SOURCES_RE = new RegExp(`(${config.elementsDir}|pfe-core)/.*\\.js`);
92+
return async function(ctx, next) {
93+
await next();
94+
if (ctx.status === 404
95+
&& !ctx.path.includes('node_modules')
96+
&& TYPESCRIPT_SOURCES_RE.test(ctx.path)) {
97+
ctx.redirect(ctx.path.replace('.js', '.ts'));
98+
}
10199
};
102100
}
103101

@@ -118,13 +116,11 @@ export function pfeDevServerConfig(options?: PfeDevServerConfigOptions): DevServ
118116
middleware: [
119117
cors,
120118
cacheBusterMiddleware,
119+
liveReloadTsChangesMiddleware(config),
121120
...config?.middleware ?? [],
122121
],
123122

124123
plugins: [
125-
// Rewrite .js paths to .ts before static file serving
126-
tsRedirectPlugin(config),
127-
128124
// Dev server app which loads component demo files
129125
pfeDevServerPlugin(config),
130126

0 commit comments

Comments
 (0)